Collections-1
Collections-1
https://nict.edu.in
5. Collections - Siddharth Arora Page 2 of 53
Generating a list – a short cut: .......................................................................................................... 15
List Example 1: .................................................................................................................................. 16
List Example 2: .................................................................................................................................. 19
List Example 3: .................................................................................................................................. 21
List Example 4 – dynamic list: ........................................................................................................... 23
List Example 5: dynamic list .............................................................................................................. 24
Nested Lists (List within a List): ......................................................................................................... 25
Dictionary: ............................................................................................................................................. 27
Declaring an empty dictionary: ......................................................................................................... 28
Declaring and initializing a dictionary: .............................................................................................. 28
Adding a new item in a dictionary: ................................................................................................... 28
Accessing an individual value using the key: .................................................................................... 28
Display the whole dictionary: ........................................................................................................... 28
Get the length of the dictionary: ...................................................................................................... 28
Delete a key-value pair from the dictionary: .................................................................................... 28
Delete all the Dictionary key-value pairs: ......................................................................................... 29
Generate a copy of a dictionary:....................................................................................................... 29
Dictionary Traversal – method 1:...................................................................................................... 29
Dictionary Traversal – method 2:...................................................................................................... 29
Search an item in the dictionary / extract the value from the key in the dictionary: ...................... 29
Dictionary Example 1: ....................................................................................................................... 30
Dictionary Example 2 (Dynamic Dictionary): .................................................................................... 32
pop() .................................................................................................................................................. 34
popitem() .......................................................................................................................................... 35
keys() ................................................................................................................................................. 36
values() .............................................................................................................................................. 36
Membership in dictionaries: ............................................................................................................. 37
Concatenate dictionaries using update(): ......................................................................................... 38
Sets:....................................................................................................................................................... 39
Declaring an Empty Set: .................................................................................................................... 39
Initializing a set at the time of its declaration: ................................................................................. 39
Display the entire set: ....................................................................................................................... 39
Get the Length of the set: ................................................................................................................. 39
Set Traversal using foreach loop: ...................................................................................................... 39
Membership – checking if an item is a part of the set or not:.......................................................... 39
Add an item in the set:...................................................................................................................... 39
https://nict.edu.in
5. Collections - Siddharth Arora Page 3 of 53
Add Multiple Items in the set (bulk addition): .................................................................................. 40
Remove an item from the set (method 1): ....................................................................................... 40
Remove an item from the set (method 2): ....................................................................................... 40
Removing the first item from the set: .............................................................................................. 40
Deleting all the items from the set: .................................................................................................. 40
Set Example 1:................................................................................................................................... 41
Set Operations: ................................................................................................................................. 43
Set Operations Example: ................................................................................................................... 44
Tuple: .................................................................................................................................................... 45
Tuple declaration (Empty): ............................................................................................................... 45
Tuple declaration & initialization: ..................................................................................................... 45
Retrieve a single Tuple Item: ............................................................................................................ 45
Get the Length of the tuple: ............................................................................................................. 45
Tuple Traversal – method 1 (syntax): ............................................................................................... 45
Tuple Traversal – using the foreach loop - method 2 (syntax): ........................................................ 45
Get Max tuple item: .......................................................................................................................... 46
Get Min tuple item:........................................................................................................................... 46
Tuple Operations: ............................................................................................................................. 46
Comparing two tuples using == ........................................................................................................ 46
Comparing two tuples using > .......................................................................................................... 46
Comparing two tuples using < .......................................................................................................... 46
Convert a list to a tuple: .................................................................................................................... 47
Convert a tuple to a list: .................................................................................................................... 47
Example:............................................................................................................................................ 48
Packing and Unpacking a Tuple: ....................................................................................................... 51
https://nict.edu.in
5. Collections - Siddharth Arora Page 4 of 53
Collections:
Python has different types of collections:
1. List
2. Dictionary
3. Tuple
4. Set
https://nict.edu.in
5. Collections - Siddharth Arora Page 5 of 53
List:
→a list is a special type of a variable that can store multiple constants.
→a list acts as a dynamic collection of data.
→a list is best suited for a scenario when a large amount of data needs to
be stored in a cluster / collection / single unit.
→at the time of declaring a list we do not need to specify the size of the
list.
→a list can expand… we can add items in a list.
→a list can shrink… we can delete items from a list.
→the same list can store different data types of data as well.
→every list item has a unique serial number called an index.
The min. index = 0
The max. index = size – 1
→every list item has a unique name by using which we can access that list
item. list_variable[index]
https://nict.edu.in
5. Collections - Siddharth Arora Page 6 of 53
List Syntax:
Declaring an empty list (syntax):
list_variable = []
Fetch the size of the list / no. of items in the list (Syntax):
len(list_variable)
https://nict.edu.in
5. Collections - Siddharth Arora Page 7 of 53
Accessing an individual List item: (syntax):
list_variable[index]
Deleting an item from the list by specifying the index: (LEFT SHIFT) (syntax)
del list_variable[index]
Deleting multiple items from the list by specifying the indexes: (LEFT SHIFT) (syntax)
del list_variable[start_index : end_index+1]
Example:
Note:
→if the item_to_delete exists in the list then it would be deleted and a left shift will take place.
→if the item_to_delete does not exist then it will throw an exception - ValueError: list.remove(x): x
not in list.
→if the item_to_delete exists multiple times then only the 1st occurrence of the item would be
deleted.
Note: pop() deletes the last item and gives the deleted item.
https://nict.edu.in
5. Collections - Siddharth Arora Page 8 of 53
Delete all the list items: (syntax):
list_variable.clear()
Note: This deletes the entire list. After this operation, the list will no longer exist.
https://nict.edu.in
5. Collections - Siddharth Arora Page 9 of 53
List Traversal – method 1 (syntax):
for index_variable in range(0, len(list_variable)):
list_variable[index_variable]
Reverse a list:
list_variable.reverse()
Note: this reverse() will reverse the existing list.
https://nict.edu.in
5. Collections - Siddharth Arora Page 10 of 53
Sorting a list in Ascending order:
list_variable.sort()
Note: this sort() will sort the same list in ascending order.
Note: this sort() will sort the same list in descending order.
https://nict.edu.in
5. Collections - Siddharth Arora Page 11 of 53
Count the occurrences of an item in a list:
Syntax:
variable = list_variable.count(item_to_search)
variable = list_variable.index(item_to_search)
Note:
→if the item exists in the list, then we will get the index of 1st occurrence.
→if the item does not exist in the list, we get an runtime error – ValueError.
note:
→in is a keyword.
→in returns True when item_to_search exists in the list.
→in returns False when item_to_search does not exist in the list.
https://nict.edu.in
5. Collections - Siddharth Arora Page 12 of 53
List Slicing:
→extracting a sub-list from a list.
Syntax 1:
Syntax 3: (when we do not specify the end_index, it goes till the end).
newlist = existinglist[start_index : ]
Syntax 4: (when we do not specify the start_index, it picks up from the beginning).
Item = existinglist[-index]
newlist = existinglist[-n : : 1]
https://nict.edu.in
5. Collections - Siddharth Arora Page 13 of 53
Concatenate a list using extend():
->This function is used to add or concatenate a list to another list.
->Syntax:
target_list_variable.extend(source_list_variable)
->Examples:
https://nict.edu.in
5. Collections - Siddharth Arora Page 14 of 53
Converting a string to a list:
Syntax:
Example:
https://nict.edu.in
5. Collections - Siddharth Arora Page 15 of 53
Generating a list – a short cut:
https://nict.edu.in
5. Collections - Siddharth Arora Page 16 of 53
List Example 1:
# Declaring a list with items
cities.append("Chennai")
cities.append("Kolkatta")
cities.insert(2, "Chandigarh")
cities[4] = "Bengaluru"
print(cities)
# Deleting an item from the list by specifying the index: (LEFT SHIFT)
https://nict.edu.in
5. Collections - Siddharth Arora Page 17 of 53
del cities[3]
# delete "Chandigarh"
cities.remove("Chandigarh")
# delete "Nagpur"
# cities.remove("Nagpur") # error
# append "Mumbai"
cities.append("Mumbai")
# delete Mumbai
# deleted_city = cities.pop()
# cities.clear()
print(cities)
print("*",cities[i])
print("*",city)
https://nict.edu.in
5. Collections - Siddharth Arora Page 18 of 53
Output:
https://nict.edu.in
5. Collections - Siddharth Arora Page 19 of 53
List Example 2:
# init. a list
list1 = [10,2,30,4,50,6,70,8,90,1]
print(list1)
list1.sort()
print(list1)
list1.reverse()
print(list1)
minitem = min(list1)
maxitem = max(list1)
list1.append(30)
print(list1)
https://nict.edu.in
5. Collections - Siddharth Arora Page 20 of 53
c = list1.count(item)
if c != 0:
elif c == 0:
x = list1.index(item)
print(item,"exists at index",x)
if res == True:
else:
https://nict.edu.in
5. Collections - Siddharth Arora Page 21 of 53
List Example 3:
# list initializaTION
# empty list declaration
list1 = []
# loop
for i in range(1,10+1,1):
# appending item in the list
list1.append(10*i)
# list1.insert(i, 10*i)
print(list1)
https://nict.edu.in
5. Collections - Siddharth Arora Page 22 of 53
newlist = list1[ : ]
print(newlist) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# list concatenation
list1 = [10,20,30]
list2 = [40,50]
list3 = [60,70,80,90]
newlist = list1 + list2 + list3
print(newlist) # [10, 20, 30, 40, 50, 60, 70, 80, 90]
# list repitiotion
list1 = [10,20,30]
newlist = list1 * 3
print(newlist) # [10, 20, 30, 10, 20, 30, 10, 20, 30]
https://nict.edu.in
5. Collections - Siddharth Arora Page 23 of 53
List Example 4 – dynamic list:
# create a list of 10 integer items input by the user. Display the list.
mylist = []
# loop - 10 times
mylist.append(item)
print(element)
Output:
https://nict.edu.in
5. Collections - Siddharth Arora Page 24 of 53
List Example 5: dynamic list
# write a program to enter all the family member names of a person in a list.
# the user should decide when to stop the inputing of the names.
# declare an empty list
family = []
print("Enter your family members names:")
# input data in the list
# infinite loop
while True:
# enter a list item
member = input("Enter name: ")
# append the item in the list
family.append(member)
# ask the user if he/she wants to exit the loop
chk = input("Do you want to stop? Y / N: ")
# check if the user wants to exit the loop
if chk == "Y" or chk == "y":
# exit the loop
break
https://nict.edu.in
5. Collections - Siddharth Arora Page 25 of 53
Nested Lists (List within a List):
→a list can even store a collection of other lists.
# Nested Lists
# create an empty list
mainlist = []
https://nict.edu.in
5. Collections - Siddharth Arora Page 26 of 53
print("Total number of lists inside the mainlist: ",len(mainlist))
# accessing the length of the lists inside the mainlist
print("Total number of items inside the 0th list of the mainlist: ",len(mainlist[0]))
print("Total number of items inside the 1st list of the mainlist: ",len(mainlist[1]))
print("Total number of items inside the 2nd list of the mainlist: ",len(mainlist[2]))
https://nict.edu.in
5. Collections - Siddharth Arora Page 27 of 53
Dictionary:
Common Name (key) Scientific Names (value)
Bison Bos gaurus
Black buck Antelope cervicapra
Chinkara Gazella bennettii
Nilgai Boselaphus tragocamelus
Wolf Canis lupus
Lion Panthera leo
https://nict.edu.in
5. Collections - Siddharth Arora Page 28 of 53
Declaring an empty dictionary:
Syntax:
dictionary_name = {}
del dictionary_name[key]
Note: if the key does not exist, we get a run time error – KeyError.
https://nict.edu.in
5. Collections - Siddharth Arora Page 29 of 53
Delete all the Dictionary key-value pairs:
Syntax:
dictionary_name.clear()
Note: here, the for loop, will generate all the keys, one key at a time.
Note: here, the for loop, will generate all the keys and values, one item at a time.
Search an item in the dictionary / extract the value from the key in the dictionary:
Syntax:
Note:
→if the “key_to_search” exists in the dictionary, then we get its value in the variable on the LHS.
→if the “key_to_search” does not exist in the dictionary, then we get the “Default_Error_value” in
the variable on the LHS.
https://nict.edu.in
5. Collections - Siddharth Arora Page 30 of 53
Dictionary Example 1:
# dictionary
# Declaring and initializing a dictionary
mammals = { 'Bison': 'Bos gaurus' , 'Black buck': 'Antelope cervicapra' }
# adding new key-value pairs in the dictionary
mammals['Chinkara'] = 'Gazella bennettii'
mammals['Nilgai'] = 'Boselaphus tragocamelus'
mammals['Wolf'] = 'Canis lupus'
# Accessing an individual value using the key
key='Black buck'
print("Scientific name for ",key," is ",mammals[key])
# key='Tiger'
# print("Scientific name for ",key," is ",mammals[key]) # error
# Display the whole dictionary
print(mammals)
# Get the length of the dictionary
print("Total number of mammals in the dictionary: ",len(mammals))
# delete the Chinkara item
del mammals['Chinkara']
# del mammals['Tiger'] # illegal
print(mammals)
# delete all the dictionary items
# mammals.clear()
# print(mammals)
# copy the dictionary
mammals2 = mammals.copy()
print("Contents of mammals: ",mammals)
print("Contents of mammals2: ",mammals2)
# dictionary traversal - method 1:
print("\nAll the mammals - using method 1:")
for x in mammals:
print("Scientific name of ",x," is ",mammals[x])
# item search:
key = input("Enter the common name of the mammal to view its scientific name: ")
value = mammals.get(key, None)
if value != None:
print(key," - ",value)
else:
print(key," does not exist")
https://nict.edu.in
5. Collections - Siddharth Arora Page 31 of 53
https://nict.edu.in
5. Collections - Siddharth Arora Page 32 of 53
Dictionary Example 2 (Dynamic Dictionary):
# Dynamic Dictionary
mammals = {}
# input key-value pairs in the dictionary till the time the user wants
# infinite loop
while True:
mammals[cname] = sname
# check
break
print("\nMammal Info:")
print(k + "("+v+")")
https://nict.edu.in
5. Collections - Siddharth Arora Page 33 of 53
https://nict.edu.in
5. Collections - Siddharth Arora Page 34 of 53
pop()
->this is a pre-defined function that removes a key-value pair from a dictionary.
->Syntax:
result_variable = dictionary_variable.pop(key)
->This function returns the value of the key in the result_variable and deletes that key-value pair.
->This functions gives an error “KeyError” if the key is not found in the dictionary.
->Example:
https://nict.edu.in
5. Collections - Siddharth Arora Page 35 of 53
popitem()
->This function deletes the last key-value pair from the dictionary.
->Syntax:
result_variable = dictionary_variable.popitem()
->This function returns a tuple of the last key-value pair that is removed from the dictionary.
->Example:
https://nict.edu.in
5. Collections - Siddharth Arora Page 36 of 53
keys()
->This pre-defined function is used to extract all the keys of a dictionary in a list.
->Syntax:
->Example:
values()
->This pre-defined function is used to extract all the values of a dictionary in a list.
->Syntax:
->Example:
https://nict.edu.in
5. Collections - Siddharth Arora Page 37 of 53
Membership in dictionaries:
->We can check the existence of a key in a dictionary using the in keyword.
->Syntax:
->This syntax returns True when key_to_search is found in dictionary otherwise returns False.
->Example:
https://nict.edu.in
5. Collections - Siddharth Arora Page 38 of 53
Concatenate dictionaries using update():
->update() is a built-in function that appends a dictionary at the end of another dictionary.
->Syntax:
target_dictionary.update( source_dictionary )
Example:
##2. Write a Python script to concatenate following dictionaries to create a new one.
##
##Sample Dictionary :
##dic1={1:10, 2:20}
##dic2={3:30, 4:40}
##dic3={5:50,6:60}
##Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
# concatenate
dic4.update(dic1)
dic4.update(dic2)
dic4.update(dic3)
# display
print(dic4)
Output:
https://nict.edu.in
5. Collections - Siddharth Arora Page 39 of 53
Sets:
→a set is a collection which is unordered and unindexed.
→items in a set can be of any data type. Even a mixed data type is allowed.
Note:
→we get True in the boolean_variable if the item_to_search is present in the set_variable.
→we get False in the boolean_variable if the item_to_search is not present in the set_variable.
https://nict.edu.in
5. Collections - Siddharth Arora Page 40 of 53
Add Multiple Items in the set (bulk addition):
set_variable.update([newitem1, newitem2, newitem3])
Note:
→if the item does not exist, it will show / throw an error (KeyError).
→if the item does not exist, it will not show / throw an error.
https://nict.edu.in
5. Collections - Siddharth Arora Page 41 of 53
Set Example 1:
# Initializing a set at the time of its declaration
cities = {"New Delhi", "Mumbai", "Chennai"}
# set traversal
print("All the cities:")
for city in cities:
print(city)
print(cities)
print(cities)
print(cities)
print(cities)
https://nict.edu.in
5. Collections - Siddharth Arora Page 42 of 53
removed_item = cities.pop()
print("Item popped: ",removed_item)
print(cities)
https://nict.edu.in
5. Collections - Siddharth Arora Page 43 of 53
Set Operations:
UNION:
→when we want to combine multiple sets and want to ensure that no duplication is there.
Union Syntax 1:
result_set_variable = set_variable_1.union(set_variable_2)
Union Syntax 2:
result_set_variable = set_variable_1 | set_variable_2
Note: both these syntaxes generate a new set where the union result is stored.
INTERSECTION:
→when we want to retrieve the common items between multiple sets.
Intersection Syntax 1:
result_set_variable = set_variable_1.intersection(set_variable_2)
Intersection Syntax 2:
result_set_variable = set_variable_1 & set_variable_2
Note: both these syntaxes generate a new set where the intersection result is stored.
DIFFERENCE:
→when we want to subtract one set items from another set.
Difference Syntax 1:
result_set_variable = set_variable_1.difference(set_variable_2)
Difference Syntax 2:
result_set_variable = set_variable_1 - set_variable_2
Note: both these syntaxes generate a new set where the difference result is stored.
https://nict.edu.in
5. Collections - Siddharth Arora Page 44 of 53
Set Operations Example:
# set operations
# set 1 initialization
car_manufacturers = {"tata","audi","suzuki","honda"}
# set 2 initialization
bike_manufacturers = {"honda","suzuki","bajaj","royal enfield"}
# union operation
all_manufacturers = car_manufacturers | bike_manufacturers
# intersection operation
both_car_bike_manufacturers = car_manufacturers & bike_manufacturers
# difference operations
only_car_manufacturers = car_manufacturers - bike_manufacturers
only_bike_manufacturers = bike_manufacturers - car_manufacturers
# display
print("\nAll the Car Manufacturers: ")
print(car_manufacturers)
print("\nAll the Bike Manufacturers: ")
print(bike_manufacturers)
print("\nAll the Manufacturers (car_manufacturers | bike_manufacturers): ")
print(all_manufacturers)
print("\nManufacturers making both Bikes and Cars (car_manufacturers & bike_manufacturers): ")
print(both_car_bike_manufacturers)
print("\nManufacturers making only Cars (car_manufacturers - bike_manufacturers): ")
print(only_car_manufacturers)
print("\nManufacturers making only Bikes (bike_manufacturers - car_manufacturers): ")
print(only_bike_manufacturers)
https://nict.edu.in
5. Collections - Siddharth Arora Page 45 of 53
Tuple:
→a tuple is a static collection.
→we cannot alter the tuple once declared.
→we cannot add new items in a tuple.
→we cannot delete items from a tuple.
→we cannot even modify the existing items stored in a tuple.
→we must initialize a tuple at its declaration time.
→a tuple can store mixed data type’s data.
→tuple is indexed (index nos. starting from 0) and ordered.
Note: cannot access a tuple beyond its size. IndexError: tuple index out of range.
https://nict.edu.in
5. Collections - Siddharth Arora Page 46 of 53
Get Max tuple item:
Note: this will only work if all the tuple items belong to the same data type.
result_variable = max(tuple_variable)
result_variable = min(tuple_variable)
Tuple Operations:
Note:
Note:
Note:
https://nict.edu.in
5. Collections - Siddharth Arora Page 47 of 53
Convert a list to a tuple:
result_tuple_variable = tuple(list_variable)
https://nict.edu.in
5. Collections - Siddharth Arora Page 48 of 53
Example:
# Tuple declaration & initialization
friends = ()
print(cities)
print(friends)
# cities[1] = "Chandigarh" # error - TypeError: 'tuple' object does not support item assignment
print(cities[i])
print(city)
https://nict.edu.in
5. Collections - Siddharth Arora Page 49 of 53
# tuple declaration
print(tup1)
maxitem = max(tup1)
minitem = min(tup1)
# tuples declaration
tup1 = (10,20,30)
tup2 = (10,25,30)
if tup1 == tup2:
else:
else:
# list
https://nict.edu.in
5. Collections - Siddharth Arora Page 50 of 53
list1 = [111,222,333,444]
print(list1)
tup1 = tuple(list1)
print(tup1)
list1 = list(tup1)
print(tup1)
print(list1)
# create a dictionary
print(dict1)
print(dict2)
https://nict.edu.in
5. Collections - Siddharth Arora Page 51 of 53
Packing and Unpacking a Tuple:
Tuple Packing:
->Syntax:
Tuple Unpacking:
->Syntax:
https://nict.edu.in
5. Collections - Siddharth Arora Page 52 of 53
Example:
# tuple packing
# initialize regular variables
var1 = 10
var2 = 20.5
var3 = "hello"
var4 = False
var5 = 789
# pack the tuple with regular variable values
tup1 = var1 , var2 , var3 , var4 , var5
# display the tuple
print(tup1)
# tuple unpacking
# declare and initialize tuple variable
cities = ("New Delhi" , "Mumbai" , "Chennai" , "Kolkatta")
# unpack the tuple into regular variables
c1, c2, c3, c4 = cities
print(c1)
print(c2)
print(c3)
print(c4)
https://nict.edu.in
5. Collections - Siddharth Arora Page 53 of 53
Output:
https://nict.edu.in