Python String, List, Tuple,
Dictionary
Python Strings
Strings
• Strings in python are surrounded by either single
quotation marks, or double quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with
the print() function:
Eg:
print("Hello")
print('Hello')
o/p:
Hello
Hello
Assign String to a Variable
Eg:
a = "Hello"
print(a)
o/p:
Hello
Multiline Strings
You can assign a multiline string to a variable by using
three quotes:
Eg:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
o/p
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
Strings are Arrays
• Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.
• However, Python does not have a character data type, a single character is
simply a string with a length of 1.
• Square brackets can be used to access elements of the string.
Eg:
a = "Hello, World!"
print(a[1])
o/p:
e
Looping Through a String
Since strings are arrays, we can loop through the
characters in a string, with a for loop.
Eg:
for x in "banana":
print(x)
o/p:
b
a
n
a
n
a
String Length
To get the length of a string, use
the len() function.
Eg:
a = "Hello, World!"
print(len(a))
o/p:
13
Check String
To check if a certain phrase or character is
present in a string, we can use the keyword in.
Eg:
txt = "The best things in life are free!"
print("free" in txt)
o/p:
True
Use it in an if statement:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
o/p:
Yes, 'free' is present.
Check if NOT
To check if a certain phrase or character is NOT
present in a string, we can use the
keyword not in.
Eg:
txt = "The best things in life are free!"
print("expensive" not in txt)
o/p:
True
Slicing Strings
Slicing
• You can return a range of characters by using the
slice syntax.
• Specify the start index and the end index,
separated by a colon, to return a part of the
string.
Eg:
b = "Hello, World!"
print(b[2:5])
o/p
llo
Slice From the Start
By leaving out the start index, the range will
start at the first character:
Eg:
b = "Hello, World!"
print(b[:5])
o/p:
Hello
Slice To the End
By leaving out the end index, the range will go to
the end:
Eg:
b = "Hello, World!"
print(b[2:])
o/p:
llo, World!
Negative Indexing
Use negative indexes to start the slice from the
end of the string:
Eg:
b = "Hello, World!"
print(b[-5:-1])
o/p:
Modify Strings
Python has a set of built-in methods that you
can use on strings.
Upper Case
The upper() method returns the string in upper
case:
a = "Hello, World!"
print([Link]())
o/p:
HELLO, WORLD!
Lower Case
The lower() method returns the string in lower
case:
Eg:
a = "Hello, World!"
print([Link]())
o/p:
hello, world!
Remove Whitespace
Whitespace is the space before and/or after the
actual text, and very often you want to remove
this space.
The strip() method removes any whitespace from
the beginning or the end:
Eg:
a = " Hello, World! "
print([Link]())
o/p:
Hello, World!
Replace String
The replace() method replaces a string with
another string:
Eg:
a = "Hello, World!"
print([Link]("H", "J"))
o/p:
Jello, World!
Split String
The split() method returns a list where the text
between the specified separator becomes the
list items.
Eg:
a = "Hello, World!"
b = [Link](",")
print(b)
o/p:
['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can
use the + operator.
Eg:
a = "Hello"
b = "World"
c=a+b
print(c)
o/p:
HelloWorld
Eg:
a = "Hello"
b = "World"
c=a+""+b
print(c)
o/p:
Hello World
Python Lists
List
• Lists are used to store multiple items in a single
variable.
• Lists are one of 4 built-in data types in Python used to
store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
Eg:
thislist = ["apple", "banana", "cherry"]
print(thislist)
o/p:
['apple', 'banana', 'cherry']
List Items
• List items are ordered, changeable, and allow duplicate
values.
• List items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered
• When we say that lists are ordered, it means that the items
have a defined order, and that order will not change.
• If you add new items to a list, the new items will be placed
at the end of the list.
Changeable
• The list is changeable, meaning that we can change, add,
and remove items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with
the same value:
Eg:
thislist = ["apple", "banana", "cherry", "apple",
"cherry"]
print(thislist)
o/p:
['apple', 'banana', 'cherry', 'apple', 'cherry']
List Length
To determine how many items a list has, use
the len() function:
Eg:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
o/p:
3
List Items - Data Types
List items can be of any data type:
Eg:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
print(list1)
print(list2)
print(list3)
o/p:
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
type()
From Python's perspective, lists are defined as
objects with the data type 'list':
<class 'list'>
Eg:
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
o/p:
<class 'list'>
The list() Constructor
It is also possible to use the list() constructor
when creating a new list.
Eg:
thislist = list(("apple", "banana", "cherry"))
print(thislist)
o/p:
['apple', 'banana', 'cherry']
Python - Access List Items
Access Items
• List items are indexed and you can access
them by referring to the index number:
Eg:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
o/p:
banana
Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the
second last item etc.
Eg:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
o/p:
cherry
Range of Indexes
• You can specify a range of indexes by specifying
where to start and where to end the range.
• When specifying a range, the return value will be
a new list with the specified items.
Eg:
thislist = ["apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango"]
print(thislist[2:5])
o/p:
['cherry', 'orange', 'kiwi']
Range of Negative Indexes
• Specify negative indexes if you want to start
the search from the end of the list:
Eg:
thislist = ["apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango"]
print(thislist[-4:-1])
o/p:
['orange', 'kiwi', 'melon']
Check if Item Exists
• To determine if a specified item is present in a
list use the in keyword:
• Eg:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
o/p:
Python - Change List Items
Change Item Value
• To change the value of a specific item, refer to
the index number:
Eg:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant“
print(thislist)
o/p:
['apple', 'blackcurrant', 'cherry']
Change a Range of Item Values
• To change the value of items within a specific
range, define a list with the new values, and refer
to the range of index numbers where you want to
insert the new values:
Eg:
thislist = ["apple", "banana", "cherry", "orange",
"kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
o/p:
['apple', 'blackcurrant', 'watermelon', 'orange',
'kiwi', 'mango']
Insert Items
• To insert a new list item, without replacing any of the
existing values, we can use the insert() method.
• The insert() method inserts an item at the specified
index:
Eg:
thislist = ["apple", "banana", "cherry"]
[Link](2, "watermelon")
print(thislist)
o/p:
['apple', 'banana', 'watermelon', 'cherry']
Append Items
To add an item to the end of the list, use
the append() method:
Eg:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
o/p:
['apple', 'banana', 'cherry', 'orange']
Insert Items
• To insert a list item at a specified index, use
the insert() method.
• The insert() method inserts an item at the
specified index:
Eg:
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)
o/p:
['apple', 'orange', 'banana', 'cherry']
Extend List
• To append elements from another list to the
current list, use the extend() method.
Eg:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)
o/p:
['apple', 'banana', 'cherry', 'mango', 'pineapple',
'papaya']
Add Any Iterable
• The extend() method does not have to
append lists, you can add any iterable object
(tuples, sets, dictionaries etc.).
Eg:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
[Link](thistuple)
print(thislist)
o/p:
['apple', 'banana', 'cherry', 'kiwi', 'orange']
Python - Remove List Items
Remove Specified Item
• The remove() method removes the specified
item.
Eg:
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist)
o/p:
['apple', 'cherry']
• If there are more than one item with the
specified value, the remove() method removes
the first occurrence:
Eg:
thislist = ["apple", "banana", "cherry", "banana",
"kiwi"]
[Link]("banana")
print(thislist)
o/p:
['apple', 'cherry', 'banana', 'kiwi']
Remove Specified Index
• The pop() method removes the specified
index.
Eg:
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)
o/p:
['apple', 'cherry']
• The del keyword also removes the specified
index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
o/p:
['banana', 'cherry']
Clear the List
• The clear() method empties the list.
• The list still remains, but it has no content.
Eg:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
o/p:
[]
Python - Loop Lists
Loop Through a List
• You can loop through the list items by using
a for loop:
Eg:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
o/p:
apple
banana
cherry
Loop Through the Index Numbers
• You can also loop through the list items by referring to
their index number.
• Use the range() and len() functions to create a suitable
iterable.
Eg:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
o/p:
apple
banana
cherry
Using a While Loop
• You can loop through the list items by using
a while loop.
• Use the len() function to determine the length of the
list, then start at 0 and loop your way through the list
items by referring to their indexes.
• Remember to increase the index by 1 after each
iteration.
• Example
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1
Python - Sort Lists
Sort List Alphanumerically
• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
Eg:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)
o/p:
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
Copy a List
• You cannot copy a list simply by typing list2 =
list1, because: list2 will only be
a reference to list1, and changes made in list1 will
automatically also be made in list2.
• There are ways to make a copy, one way is to use
the built-in List method copy()
Eg:
thislist = ["apple", "banana", "cherry"]
mylist = [Link]()
print(mylist)
o/p:
['apple', 'banana', 'cherry']
Join Two Lists
• There are several ways to join, or concatenate, two or
more lists in Python.
• One of the easiest ways are by using the + operator.
Eg:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
o/p:
['a', 'b', 'c', 1, 2, 3]
Python Tuples
mytuple = ("apple", "banana", "cherry")
Tuple
• Tuples are used to store multiple items in a single
variable.
• Tuple is one of 4 built-in data types in Python
used to store collections of data, the other 3
are List, Set, and Dictionary, all with different
qualities and usage.
• A tuple is a collection which is ordered
and unchangeable.
• Tuples are written with round brackets.
Eg:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
o/p:
('apple', 'banana', 'cherry')
Tuple Items
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
• Ordered
• When we say that tuples are ordered, it means that the items have
a defined order, and that order will not change.
• Unchangeable
• Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
• Allow Duplicates
• Since tuples are indexed, they can have items with the same value:
Tuple Length
• To determine how many items a tuple has, use
the len() function:
Eg:
thistuple = tuple(("apple", "banana", "cherry"))
print(len(thistuple))
o/p:
3
Tuple Items - Data Types
• Tuple items can be of any data type:
• Eg:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
o/p:
('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)
The tuple() Constructor
• It is also possible to use
the tuple() constructor to make a tuple.
EG:
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
o/p:
('apple', 'banana', 'cherry')
Python - Access Tuple Items
• You can access tuple items by referring to the
index number, inside square brackets:
• Eg:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
o/p:
banana
Negative Indexing
• Negative indexing means start from the end.
• -1 refers to the last item, -2 refers to the second
last item etc.
Eg:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
o/p:
cherry
Range of Indexes
• You can specify a range of indexes by specifying
where to start and where to end the range.
• When specifying a range, the return value will be
a new tuple with the specified items.
Eg:
thistuple = ("apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango")
print(thistuple[2:5])
o/p:
('cherry', 'orange', 'kiwi')
Python - Update Tuples
• Tuples are unchangeable, meaning that you cannot change, add, or
remove items once the tuple is created.
• But there are some workarounds. You can convert the tuple into a
list, change the list, and convert the list back into a tuple.
Eg:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
o/p:
("apple", "kiwi", "cherry")
Add Items
• Since tuples are immutable, they do not have a built-
in append() method, but there are other ways to add items to a
tuple.
• 1. Convert into a list: Just like the workaround for changing a tuple,
you can convert it into a list, add your item(s), and convert it back
into a tuple.
Eg:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)
print(thistuple)
o/p:
('apple', 'banana', 'cherry', 'orange')
Add tuple to a tuple. You are allowed to add
tuples to tuples, so if you want to add one
item, (or many), create a new tuple with the
item(s), and add it to the existing tuple:
Eg:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
o/p:
('apple', 'banana', 'cherry', 'orange')
Remove Items:
Tuples are unchangeable, so you cannot remove
items from it, but you can use the same
workaround as we used for changing and adding
tuple items:
Eg:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)
print(thistuple)
o/p:
('banana', 'cherry')
• The del keyword can delete the tuple completely:
Eg:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple)
o/p:
Traceback (most recent call last)
File "demo_tuple_del.py", line 3, in <module>
print(thistuple) #this will raise an error because the
tuple no longer exists
NameError: name 'thistuple' is not defined
Python - Unpack Tuples
Unpacking a Tuple
• When we create a tuple, we normally assign
values to it. This is called "packing" a tuple:
Eg:
fruits = ("apple", "banana", "cherry")
print(fruits)
o/p:
('apple', 'banana', 'cherry')
But, in Python, we are also allowed to extract the values
back into variables. This is called "unpacking":
Eg:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
o/p:
apple
banana
cherry
Using Asterisk*
• If the number of variables is less than the number of
values, you can add an * to the variable name and the
values will be assigned to the variable as a list:
Eg:
fruits = ("apple", "banana", "cherry", "strawberry",
"raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
o/p:
apple
banana
['cherry', 'strawberry', 'raspberry']
Python - Loop Tuples
Loop Through a Tuple
• You can loop through the tuple items by using
a for loop.
Eg:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
o/p:
apple
Banana
cherry
Loop Through the Index Numbers
• You can also loop through the tuple items by
referring to their index number.
• Use the range() and len() functions to create a
suitable iterable.
Eg:
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
o/p:
apple
banana
cherry
Using a While Loop
• You can loop through the tuple items by using a while loop.
• Use the len() function to determine the length of the tuple, then
start at 0 and loop your way through the tuple items by referring to
their indexes.
• Remember to increase the index by 1 after each iteration.
Eg:
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
o/p:
apple
banana
cherry
Python - Join Tuples
Join Two Tuples
• To join two or more tuples you can use
the + operator:
Eg:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
o/p:
('a', 'b', 'c', 1, 2, 3)
Multiply Tuples
• If you want to multiply the content of a tuple a
given number of times, you can use
the * operator:
Eg:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
o/p:
('apple', 'banana', 'cherry', 'apple', 'banana',
'cherry')
Python Sets
myset = {"apple", "banana", "cherry"}
Set
• Sets are used to store multiple items in a
single variable.
• Set is one of 4 built-in data types in Python
used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with
different qualities and usage.
• A set is a collection which
is unordered, unchangeable*, and unindexed.
Set Items
• Set items are unordered, unchangeable, and do not
allow duplicate values.
Unordered
• Unordered means that the items in a set do not have a
defined order.
• Set items can appear in a different order every time
you use them, and cannot be referred to by index or
key.
Unchangeable
• Set items are unchangeable, meaning that we cannot
change the items after the set has been created.
Duplicates Not Allowed
• Sets cannot have two items with the same value.
Eg:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
o/p:
{'banana', 'cherry', 'apple'}
Get the Length of a Set
• To determine how many items a set has, use
the len() function.
Eg:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
o/p:
3
Set Items - Data Types
• Set items can be of any data type:
Eg:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)
o/p:
{'cherry', 'apple', 'banana'}
{1, 3, 5, 7, 9}
{False, True}
type()
• From Python's perspective, sets are defined as
objects with the data type 'set':
• <class 'set'>
Eg:
myset = {"apple", "banana", "cherry"}
print(type(myset))
o/p:
<class 'set'>
The set() Constructor
• It is also possible to use the set() constructor
to make a set.
Eg:
thisset = set(("apple", "banana", "cherry"))
print(thisset)
o/p:
{'banana', 'apple', 'cherry'}
Python - Access Set Items
Access Items
• You cannot access items in a set by referring to an index or
a key.
• But you can loop through the set items using a for loop, or
ask if a specified value is present in a set, by using
the in keyword.
Eg:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
o/p:
banana
Cherry
apple
Python - Add Set Items
Add Items
• Once a set is created, you cannot change its
items, but you can add new items.
Eg:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
o/p:
{'banana', 'orange', 'apple', 'cherry'}
Add Sets
• To add items from another set into the current
set, use the update() method.
Eg:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)
o/p:
{'apple', 'mango', 'cherry', 'pineapple', 'banana',
'papaya'}
Add Any Iterable
• The object in the update() method does not have
to be a set, it can be any iterable object (tuples,
lists, dictionaries etc.).
Eg:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
[Link](mylist)
print(thisset)
o/P
{'banana', 'cherry', 'apple', 'orange', 'kiwi'}
Python - Remove Set Items
Remove Item
• To remove an item in a set, use the remove(), or
the discard() method.
Eg:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
o/p:
{'cherry', 'apple'}
If the item to remove does not exist, remove() will
raise an error.
Remove "banana" by using
the discard() method:
Eg:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
o/p:
{'apple', 'cherry'}
• You can also use the pop() method to remove an item, but
this method will remove a random item, so you cannot be
sure what item that gets removed.
• The return value of the pop() method is the removed item.
Eg:
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x) #removed item
print(thisset) #the set after removal
o/p:
Cherry
{'apple', 'banana'}
• The clear() method empties the set:
Eg:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
o/p:
set()
• The del keyword will delete the set completely:
Eg:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset) #this will raise an error because the set no
longer exists
o/p:
Traceback (most recent call last):
File "demo_set_del.py", line 5, in <module>
print(thisset) #this will raise an error because the set
no longer exists
NameError: name 'thisset' is not defined
Python - Loop Sets
Loop Items
• You can loop through the set items by using
a for loop:
Eg:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
o/p:
Cherry
Apple
banana
Python - Join Sets
Join Sets
• There are several ways to join two or more sets in
Python.
• The union() and update() methods joins all items
from both sets.
• The intersection() method keeps ONLY the
duplicates.
• The difference() method keeps the items from
the first set that are not in the other set(s).
• The symmetric_difference() method keeps all
items EXCEPT the duplicates.
Union
• The union() method returns a new set with all
items from both sets.
Eg:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
o/p:
{1, 'b', 'a', 2, 'c', 3}
You can use the | operator instead of
the union() method, and you will get the same
result.
Eg:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1 | set2
print(set3)
o/p:
{'c', 'a', 'b', 2, 1, 3}
Join Multiple Sets
• All the joining methods and operators can be used to join
multiple sets.
• When using a method, just add more sets in the
parentheses, separated by commas:
Eg:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = [Link](set2, set3, set4)
print(myset)
o/p:
{2, apple, John, Elena, 3, 'a', cherry, banana, 'c', 'b', 1}
When using the | operator, separate the sets with
more | operators:
Eg:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = set1 | set2 | set3 |set4
print(myset)
o/p:
{'b', cherry, apple, John, 'c', 2, banana, 'a', Elena, 1,
3}
Join a Set and a Tuple
• The union() method allows you to join a set
with other data types, like lists or tuples.
• The result will be a set.
Eg:
x = {"a", "b", "c"}
y = (1, 2, 3)
z = [Link](y)
print(z)
o/p:
{3, 1, 'b', 'c', 2, 'a'}
Update
• The update() method inserts all items from one
set into another.
• The update() changes the original set, and does
not return a new set.
Eg:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
[Link](set2)
print(set1)
o/p:
{3, 'a', 'b', 1, 2, 'c'}
Intersection
• Keep ONLY the duplicates
• The intersection() method will return a new set,
that only contains the items that are present in
both sets.
Eg:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = [Link](set2)
print(set3)
o/p:
You can use the & operator instead of
the intersection() method, and you will get the
same result.
Eg:
set1 = {"apple", "banana" , "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 & set2
print(set3)
o/p:
Difference
• The difference() method will return a new set
that will contain only the items from the first set
that are not present in the other set.
Eg:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = [Link](set2)
print(set3)
o/p:
Set symmetric_difference() Method
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
o/p:
{'microsoft', 'banana', 'google', 'cherry'}
Python Dictionaries
Dictionary
• Dictionaries are used to store data values in
key:value pairs.
• A dictionary is a collection which is ordered*,
changeable and do not allow duplicates.
• As of Python version 3.7, dictionaries
are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
• Dictionaries are written with curly brackets, and
have keys and values:
Duplicates Not Allowed
• Dictionaries cannot have two items with the
same key:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items
• Dictionary items are ordered, changeable, and do not allow duplicates.
• Dictionary items are presented in key:value pairs, and can be referred to
by using the key name.
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
o/p:
Ford
Dictionary Length
• To determine how many items a dictionary has, use
the len() function:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
o/p:
3
Dictionary Items - Data Types
• The values in dictionary items can be of any data type:
Eg:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)
o/p:
{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors':
['red', 'white', 'blue']}
type()
• From Python's perspective, dictionaries are defined as
objects with the data type 'dict':
<class 'dict'>
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
o/p:
<class 'dict'>
The dict() Constructor
• It is also possible to use the dict() constructor
to make a dictionary.
Eg:
thisdict = dict(name = "John", age = 36, country
= "Norway")
print(thisdict)
o/p:
{'name': 'John', 'age': 36, 'country': 'Norway'}
Python - Access Dictionary Items
Accessing Items
• You can access the items of a dictionary by referring to
its key name, inside square brackets:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
o/p:
Mustang
There is also a method called get() that will give you the same
result:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("model")
print(x)
o/p:
Mustang
Get Keys
• The keys() method will return a list of all the keys in the
dictionary.
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
o/p:
dict_keys(['brand', 'model', 'year'])
Get Values
• The values() method will return a list of all the values in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
O/P:
dict_values(['Ford', 'Mustang', 1964])
Get Items
• The items() method will return each item in a dictionary, as tuples
in a list.
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
o/p:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Python - Change Dictionary Items
Change Values
• You can change the value of a specific item by referring to
its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Update Dictionary
• The update() method will update the dictionary with the items from
the given argument.
• The argument must be a dictionary, or an iterable object with
key:value pairs.
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
print(thisdict)
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Python - Add Dictionary Items
Adding Items
• Adding an item to the dictionary is done by using a new
index key and assigning a value to it:
• Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Update Dictionary
• The update() method will update the dictionary with the items from
a given argument. If the item does not exist, the item will be added.
• The argument must be a dictionary, or an iterable object with
key:value pairs.
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "red"})
print(thisdict)
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Python - Remove Dictionary Items
Removing Items
• There are several methods to remove items from a
dictionary:
• The pop() method removes the item with the specified key
name:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
o/p:
{'brand': 'Ford', 'year': 1964}
The popitem() method removes the last inserted item (in
versions before 3.7, a random item is removed
instead):
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
o/p:
{'brand': 'Ford', 'model': 'Mustang'}
The del keyword removes the item with the
specified key name:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
o/p:
{'brand': 'Ford', 'year': 1964}
The clear() method empties the dictionary:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
o/p:
{}
Python - Loop Dictionaries
Loop Through a Dictionary
• You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
o/p:
Brand
Model
year
• Print all values in the dictionary, one by one:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
o/p:
Ford
Mustang
1964
You can also use the values() method to return values of a
dictionary:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in [Link]():
print(x)
o/p:
Ford
Mustang
1964
You can use the keys() method to return the keys of a dictionary:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in [Link]():
print(x)
o/p:
brand
model
year
Loop through both keys and values, by using the items() method:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in [Link]():
print(x, y)
o/p:
brand Ford
model Mustang
year 1964
Python - Copy Dictionaries
Copy a Dictionary
• You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
• There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
Make a copy of a dictionary with the copy() method:
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Another way to make a copy is to use the built-in
function dict().
Eg:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}