07-05-2023
Collection data types in
Python
By
[Link] Jain
IIIT Nagpur
Collection data types in Python
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered and unindexed. No duplicate
members.
• Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.
1
07-05-2023
Lists
A list in Python is an ordered group of items or elements, and these list
elements don't have to be of the same type.
Python Lists are mutable objects that can change their values.
A list contains items separated by commas and enclosed within square
brackets.
List indexes like strings starting at 0 in the beginning of the list and
working their way from -1 at the end.
Similar to strings, Lists operations include slicing ([ ] and [:]) ,
concatenation (+), repetition (*), and membership (in).
This example shows how to access, update and delete list elements:
Lists
• L1=[1,2,4,5,’Pooja’,’iiitn’]
print(L1)
• Access
access the list items by referring to the index number:
L1[2]
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second last item etc.
L1[-1] -Last item
2
07-05-2023
Range of indexes
• print(L1[2:5]
• the return value will be a new list with the specified items.
• print(L1[:4])
• print(L1[2:])
• print(L1[-4:-1])
Modifications
• To change the value of a specific item, refer to the index number:
L1[1]=‘Nagpur’
• Loop Through a List
for x in L1:
print(x)
• Check if Item Exists
if "apple" in L1:
print("Yes, 'apple' is in the fruits list")
• Length
print(len(L1))
3
07-05-2023
Adding items
• To add an item to the end of the list, use the append() method:
[Link]("orange")
• To add an item at the specified index, use the insert() method:
[Link](1, "orange")
Deleting items
• The remove() method removes the specified item:
[Link](“iiit")
• The pop() method removes the specified index, (or the last item if index is
not specified):
[Link]()
• The del keyword removes the specified index:
del L1[0]
• The del keyword can also delete the list completely:
del L1
The clear() method empties the list:
[Link]()
4
07-05-2023
Copy a List
• 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().
mylist = [Link]()
• Another way to make a copy is to use the built-in method list().
mylist = list(L1)
Join Two Lists
• list3 = list1 + list2
• Append list2 into list1:
for x in list2:
[Link](x)
• the extend() method, which purpose is to add elements from one list to
another list:
[Link](list2)
• The list() Constructor-to make a new list.
L1 = list(("apple", "banana", "cherry")) # double round-brackets
print(thislist)
5
07-05-2023
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Tuples
• A tuple is a collection which is ordered and unchangeable. In Python
tuples are written with round brackets.
tup=(“iiit",”nagpur",”keyboard")
print(thistuple)
Accessing an element
print(tup[1])
print(tup[-1])
print(tup[2:5])
print(tup[-4:-1])
6
07-05-2023
Change values
• Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
• But there is a workaround. Convert the tuple into a list, change the list, and
convert the list back into a tuple.
• x = (“keyboard", “mouse", “laptop")
y = list(x)
y[1] = “desk"
x = tuple(y)
print(x)
• Once a tuple is created, one cannot add items to it. Tuples
are unchangeable.
Loop through a tuple
• for x in thistuple:
print(x)
• Check if Item Exists
• if “mouse" in thistuple:
print("Yes, ‘mouse' is in the tuple")
7
07-05-2023
Delete items to a tuple
• The del keyword can delete the tuple completely:
del tup
print(tup) #this will raise an error because the tuple no longer exists
Join Two Tuples
• tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
• Tuple constructor
thistuple = tuple(("apple", "banana", "cherry")) # note the double
round-brackets
print(thistuple)
8
07-05-2023
Tuple methods
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was
found
Sets
• A set is a collection which is unordered and unindexed. In Python sets
are written with curly brackets.
aset = {“mango”, ”apple”, “banana”, “pineapple”}
print(aset)
Sets are unordered, not sure in which order the items will appear
9
07-05-2023
Accessing items in sets
• Cannot access items in a set by referring to an index, since sets are
unordered the items has no index.
aset = {“mango”, ”apple”, “banana”, “pineapple”}
print(aset)
for x in aset:
print(x)
Checking and modifications
• Checking if an element is present in set
print(“apple” in aset)
Once a set is created, its items cannot be changed but new items can
be added
To add one item to a set -add() method.
To add more than one item to a set -update() method.
[Link](“blackberry”)
[Link]([“orange”,”mango”]
10
07-05-2023
Length and deletion
• Length of a Set
print(len(aset))
• Remove item
[Link](“apple”)
[Link](“apple”)
If the item to remove does not exist, remove() will raise an error.
The clear() method empties the set
[Link]()
Deleting a and joining sets
• The del keyword will delete the set completely:
del(aset)
• Join
union() method returns a new set containing all items from both sets,
update() method inserts all the items from one set into another:
set3 = [Link](set2)
[Link](set2)
Both union() and update() will exclude any duplicate items.
11
07-05-2023
The set() Constructor
• Using the set() constructor to make a set:
aset = set(("apple", "banana", "cherry")) # double round-brackets
print(aset)
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
12
07-05-2023
Dictionary
• A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets, and
they have keys and values.
• Dict={‘Name’:’Pooja’,’Gender’:’Female’,’Organization’:’IIITN’}
• 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.
• Dictionaries are written with curly brackets, and have keys and values:
Accessing items
• X=Dict[‘Name’]
• There is also a method called get() that will gives the same result:
x = [Link](“Name")
• Change value
Dict[“Name"] = ’Rahul’
• Loop through a dictionary
for x in Dict:
print(x)
13
07-05-2023
Operations on Dictionary
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert
the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
14