0% found this document useful (0 votes)
13 views53 pages

Collections-1

This document discusses Python collections including lists, dictionaries, and sets. It provides syntax examples for common operations on each type of collection such as declaring, initializing, accessing/modifying elements, traversing, sorting, counting occurrences, slicing, concatenating, and more. Lists can contain heterogeneous elements and allow duplicates while dictionaries contain unique keys that map to values. Sets contain unique elements like dictionaries but are unordered.

Uploaded by

Akshit Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views53 pages

Collections-1

This document discusses Python collections including lists, dictionaries, and sets. It provides syntax examples for common operations on each type of collection such as declaring, initializing, accessing/modifying elements, traversing, sorting, counting occurrences, slicing, concatenating, and more. Lists can contain heterogeneous elements and allow duplicates while dictionaries contain unique keys that map to values. Sets contain unique elements like dictionaries but are unordered.

Uploaded by

Akshit Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

5.

Collections - Siddharth Arora Page 1 of 53


Collections:
Table of Contents
Collections:.............................................................................................................................................. 4
List: .......................................................................................................................................................... 5
List Syntax: .......................................................................................................................................... 6
Declaring an empty list (syntax):......................................................................................................... 6
Declaring a list with items / non-empty list (Syntax): ......................................................................... 6
Appending (adding at end) an item in a list (syntax): ......................................................................... 6
Adding an item at a specific index (position) in the list: (syntax): ...................................................... 6
Display the list’s contents in a pre-defined manner (syntax): ............................................................ 6
Replace an item at an index of a list (syntax): .................................................................................... 6
Fetch the size of the list / no. of items in the list (Syntax):................................................................. 6
Accessing an individual List item: (syntax):......................................................................................... 7
Deleting an item from the list by specifying the index: (LEFT SHIFT) (syntax).................................... 7
Deleting multiple items from the list by specifying the indexes: (LEFT SHIFT) (syntax) ..................... 7
Deleting an item by specifying the item to delete: (LEFT SHIFT) (Syntax): ......................................... 7
Deleting the last item from the List: (syntax): .................................................................................... 7
Delete all the list items: (syntax): ....................................................................................................... 8
Delete the list: (syntax): ...................................................................................................................... 8
List Traversal – method 1 (syntax): ..................................................................................................... 9
List Traversal – using the foreach loop - method 2 (syntax): .............................................................. 9
Reverse a list: ...................................................................................................................................... 9
Get the minimum item of a list: .......................................................................................................... 9
Get the maximum item of a list: ......................................................................................................... 9
Sorting a list in Ascending order: ...................................................................................................... 10
Sorting a list in Descending order: .................................................................................................... 10
Sorting a List of String according to length: ...................................................................................... 10
Count the occurrences of an item in a list: ....................................................................................... 11
Get the index of an item if it exists: .................................................................................................. 11
Membership – check whether an item exists in a list using “in”:..................................................... 11
List Slicing: ......................................................................................................................................... 12
List concatenation (joining of lists): .................................................................................................. 12
List repetition (repeating a list a number of times): ......................................................................... 12
Concatenate a list using extend(): .................................................................................................... 13
Converting a string to a list: .............................................................................................................. 14

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 = []

Declaring a list with items / non-empty list (Syntax):


list_variable = [item1, item2, item3, … ,itemN]

Appending (adding at end) an item in a list (syntax):


list_variable.append(new_item)

Adding an item at a specific index (position) in the list: (syntax):


list_variable.insert(index , newitem)
Note:
→if we give a valid index then right shift takes place in the list.
→if we give an invalid index then it appends the item at the end of the
list.

Display the list’s contents in a pre-defined manner (syntax):


print(list_variable)

Replace an item at an index of a list (syntax):


list_variable[index] = new_value
Note: if we give an invalid index, we will get an error.
IndexError: list assignment index out of range

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]

Note: if we give an invalid index, we will get an error.

IndexError: list assignment index out of range

Deleting an item from the list by specifying the index: (LEFT SHIFT) (syntax)
del list_variable[index]

Note: if we give an invalid index, we will get an error.

IndexError: list assignment index out of range

Deleting multiple items from the list by specifying the indexes: (LEFT SHIFT) (syntax)
del list_variable[start_index : end_index+1]

Example:

Deleting an item by specifying the item to delete: (LEFT SHIFT) (Syntax):


list_variable.remove(item_to_delete)

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.

Deleting the last item from the List: (syntax):


deleted_item = list_variable.pop()

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()

Delete the list: (syntax):


del list_variable

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]

List Traversal – using the foreach loop - method 2 (syntax):


for temp_variable in list_variable:
temp_variable
Note:
→the foreach loop auto starts from the 0-index position.
→the foreach loop auto increments by 1 index position.
→the foreach loop auto stops on reaching the end.

Reverse a list:
list_variable.reverse()
Note: this reverse() will reverse the existing list.

Get the minimum item of a list:


variable = min(list_variable)
Note: min() only works in a list where all the elements are of the same datatype.

Get the maximum item of a list:


variable = max(list_variable)
Note: max() only works in a list where all the elements are of the same datatype.

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.

Sorting a list in Descending order:


list_variable.sort(reverse=True)

Note: this sort() will sort the same list in descending order.

Sorting a List of String according to length:


list_variable.sort(key=len)

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)

Note: count() returns 0 if item_to_search not found in the list.

Get the index of an item if it exists:


Syntax:

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.

Membership – check whether an item exists in a list using “in”:


Syntax:
boolean_result_variable = item_to_search in list_variable

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.

→generating a new list from an existing list.

Syntax 1:

newlist = existinglist[start_index : end_index+1 : step_value]

Syntax 2: (step_value is optional if you want to increment 1)

newlist = existinglist[start_index : end_index+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).

newlist = existinglist[ : end_index+1 ]

Syntax 5: extracting item from the end

Item = existinglist[-index]

Syntax 6: extract the last n items from the list

newlist = existinglist[-n : : 1]

Syntax 7: Reversing the list:

result_list = existinglist[-1 : : -1]

List concatenation (joining of lists):


Syntax:

result_list = list1 + list2 + list3

List repetition (repeating a list a number of times):


Syntax:

result_list = list1 * number_of_repititions

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:

result_list_variable = list( string_variable )

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 = ["New Delhi" , "Mumbai"]

# Appending (adding at end) items in a list

cities.append("Chennai")

cities.append("Kolkatta")

# insert Chandigarh at index 2

cities.insert(2, "Chandigarh")

# insert Mohali at index 9

cities.insert(9, "Mohali") # legal

# change the index 4 item with Bengaluru

cities[4] = "Bengaluru"

# change the index 9th item with Amritsar

# cities[9] = "Amritsar" # illegal as 9th index does not exist

# Display the list’s contents in a pre-defined manner

print(cities)

# Fetch the size of the list / no. of items in the list

print("Total no. of cities in the collection: ",len(cities))

# Accessing an individual List item:

print("City at index 2: ",cities[2])

print("City at index 4: ",cities[4])

# print("City at index 20: ",cities[20]) # error

# Deleting an item from the list by specifying the index: (LEFT SHIFT)

# delete item at index 3:

https://nict.edu.in
5. Collections - Siddharth Arora Page 17 of 53
del cities[3]

# del cities[20] # illegal

# Deleting an item by specifying the item to delete: (LEFT SHIFT)

# delete "Chandigarh"

cities.remove("Chandigarh")

# delete "Nagpur"

# cities.remove("Nagpur") # error

# append "Mumbai"

cities.append("Mumbai")

# delete Mumbai

# cities.remove("Mumbai") # only the 1st Mumbai would be deleted.

# Deleting the last item from the List:

# deleted_city = cities.pop()

# print("Popped City: ",deleted_city)

# delete all the items

# cities.clear()

print(cities)

# List Traversal – method 1

print("\nAll the cities (using for): ")

for i in range(0, len(cities)):

print("*",cities[i])

# List Traversal – method 2

print("\nAll the cities (using foreach): ")

for city in cities:

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("List before sorting:")

print(list1)

# Sorting a list in Ascending order

list1.sort()

print("List After sorting in ascending order:")

print(list1)

# Reverse the list

list1.reverse()

print("List After reversing:")

print(list1)

# Get the minimum item of a list

minitem = min(list1)

print("Smallest item of the list: ",minitem)

# Get the maximum item of a list

maxitem = max(list1)

print("Largest item of the list: ",maxitem)

# appending 30 in the list

list1.append(30)

print(list1)

# Count the occurrences of an item in a list

item = int(input("Enter item to search: "))

https://nict.edu.in
5. Collections - Siddharth Arora Page 20 of 53
c = list1.count(item)

if c != 0:

print(item, "exists",c,"times in the list.")

elif c == 0:

print(item,"not found in the list")

# Get the index of an item if it exists

item = int(input("Enter item to search: "))

x = list1.index(item)

print(item,"exists at index",x)

# Membership – check whether an item exists in a list using “in”:

item = int(input("Enter item to search: "))

res = item in list1

if res == True:

print(item,"exists in the list")

else:

print(item,"does not exist in the list")

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)

# list slicing - syntax 1


# extract item from the list starting from the 3rd index to the 7th index
newlist = list1[3 : 7+1 : 1]
print(newlist) # [40, 50, 60, 70, 80]
# extract item from the list starting from the 1st index to the 8th index. pick every alternate item
newlist = list1[1 : 8+1 : 2]
print(newlist) # [20, 40, 60, 80]

# list slicing - syntax 2


# extract item from the list starting from the 3rd index to the 7th index
newlist = list1[3 : 7+1]
print(newlist) # [40, 50, 60, 70, 80]

# list slicing - syntax 3


# extract item from the list starting from the 3rd index
newlist = list1[3 : ]
print(newlist) # [40, 50, 60, 70, 80, 90, 100]

# list slicing - syntax 4


# extract item from the list ending at the 7rd index
newlist = list1[ : 7+1 ]
print(newlist) # [10, 20, 30, 40, 50, 60, 70, 80]

# extracting item from the end


lastitem = list1[-1]
print(lastitem) # 100
seclastitem = list1[-2]
print(seclastitem) # 90

# last three items - reverse order


newlist = list1[-1 : -4 : -1]
print(newlist) # [100, 90, 80]

# last three items - regular order


newlist = list1[-3 : : 1]
print(newlist) # [80, 90, 100]

# copy a list to another list

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.

# declare an empty list

mylist = []

print("Enter items in the list:")

# loop - 10 times

for i in range(1, 10+1):

# input an item from the user

item = int(input("Enter an item: "))

# append the item in the list

mylist.append(item)

print("\nItems in the list:")

# display the list - loop - foreach

for element in mylist:

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

print("\nYour Family members:")


# display the list - loop - foreach
for member in family:
print(member)

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 = []

# creating a sub list


sublist1 = [10,20,30]
# creating a sub list
sublist2 = [40,50,60]
# creating a sub list
sublist3 = [70,80,90]

# append the sublist1 in the mainlist


mainlist.append(sublist1) # this item gets added at the 0 index of the mainlist
# append the sublist2 in the mainlist
mainlist.append(sublist2) # this item gets added at the 1 index of the mainlist
# append the sublist3 in the mainlist
mainlist.append(sublist3) # this item gets added at the 2 index of the mainlist

# display the mainlist


print(mainlist)

# display the lists stored inside the list of lists (mainlist)


print("List stored at the 0 index of the mainlist: ",mainlist[0])
print("List stored at the 1 index of the mainlist: ",mainlist[1])
print("List stored at the 2 index of the mainlist: ",mainlist[2])

# display the items stored inside the list of lists


# 0th list items
print("0th list items")
print("Item stored at the 0th index of the 0th list: ",mainlist[0][0])
print("Item stored at the 1st index of the 0th list: ",mainlist[0][1])
print("Item stored at the 2nd index of the 0th list: ",mainlist[0][2])
# 1st list items
print("1st list items")
print("Item stored at the 0th index of the 1st list: ",mainlist[1][0])
print("Item stored at the 1st index of the 1st list: ",mainlist[1][1])
print("Item stored at the 2nd index of the 1st list: ",mainlist[1][2])
# 2nd list items
print("2nd list items")
print("Item stored at the 0th index of the 2nd list: ",mainlist[2][0])
print("Item stored at the 1st index of the 2nd list: ",mainlist[2][1])
print("Item stored at the 2nd index of the 2nd list: ",mainlist[2][2])

# accessing the length of the entire lists of lists

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]))

# accessing / displaying the list items in rows and columns, as a matrix:


# outer loop - rows
for i in range(0, len(mainlist)):
# inner loop - columns
for j in range(0, len(mainlist[i])):
# access the element
print(mainlist[i][j], end="\t")
# line break
print()

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

→In a variable we can only store a single type of information.


We cannot store multiple data items in a single variable.
→Dictionary is a dynamic collection of data.
→we can create an empty dictionary.
→we can add items in a dictionary.
→we can remove items from a dictionary.
→no size needs to be specified at the time of dictionary declaration.
→we can only store key-value pairs in a dictionary.
→Both key and value can be of any data type.
→in a dictionary the order does not matter. When we insert an item in a
dictionary, it can be inserted in any position.

https://nict.edu.in
5. Collections - Siddharth Arora Page 28 of 53
Declaring an empty dictionary:
Syntax:
dictionary_name = {}

Declaring and initializing a dictionary:


Syntax:
dictionary_name = { key: value , key: value , key : value}

Adding a new item in a dictionary:


Syntax:
dictionary_name[key] = value

Accessing an individual value using the key:


Syntax:
dictionary_name[key]
Note: if the key does not exist, we get a run time error – KeyError.

Display the whole dictionary:


Syntax:
print(dictionary_name)

Get the length of the dictionary:


→the number of key-value pairs.
Syntax:
len(dictionary_name)

Delete a key-value pair from the dictionary:


Syntax:

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()

Generate a copy of a dictionary:


Syntax:
Target_dictionary = source_dictionary.copy()
Note: a new dictionary, the Target_dictionary gets auto-created with the source_dictionary’s
contents.

Dictionary Traversal – method 1:


Traversal: accessing each dictionary item, one item at a Time, starting from the 1st item to the last
item.
Syntax:
for key_var in dictionary_name:
to access the key use: key_var
to access the value use: dictionary_name[key_var]

Note: here, the for loop, will generate all the keys, one key at a time.

Dictionary Traversal – method 2:


Syntax:
for key_var, value_var in dictionary_name.items():
to access the key use: key_var
to access the value use: value_var

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:

Value_variable = Dictionary_name.get(key_to_search , Default_Error_value)

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.

→error does not appear if the key does not exist.

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])

# dictionary traversal - method 2:


print("\nAll the mammals - using method 2:")
for x,y in mammals.items():
print(x," : ",y)

# 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

# enter the key-value pairs from the user

# create an empty dictionary

mammals = {}

# input key-value pairs in the dictionary till the time the user wants

print("\nEnter mammal info:")

# infinite loop

while True:

# get the key (common name) from the user

cname = input("Enter common name of mammal: ")

# get the value (Scientific name) from the user

sname = input("Enter scientific name of mammal: ")

# add the key-value pair in the dictionary

mammals[cname] = sname

# check if the user wants to exit the infinite loop

chk = input("Press Y to exit: ")

# check

if chk == "Y" or chk == "y":

# exit the loop

break

# display the key-value pairs of the dictionary

print("\nMammal Info:")

# traverse the dictionary

for k,v in mammals.items():

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:

result_list_variable = list( dictionary_variable.keys() )

->This function returns a list full of keys from a dictionary.

->Example:

values()
->This pre-defined function is used to extract all the values of a dictionary in a list.

->Syntax:

result_list_variable = list( dictionary_variable.values() )

->This function returns a list full of values from a dictionary.

->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:

boolean_result_value = key_to_search in dictionary_variable

->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}

# dictionary declaration & initialization


dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}

# empty dictionary declaration


dic4 = {}

# 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.

→a set can only store unique items.

→items in a set can be of any data type. Even a mixed data type is allowed.

Declaring an Empty Set:


set_variable = set()

Initializing a set at the time of its declaration:


set_variable = {value1, value2, value3, … , value_n}

Display the entire set:


print(set_variable)

Get the Length of the set:


len(set_variable)

Set Traversal using foreach loop:


for temp_variable in set_variable:

access each item using temp_variable

Membership – checking if an item is a part of the set or not:


boolean_variable = item_to_search in set_variable

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.

Add an item in the set:


set_variable.add(new_item)

Note: we cannot add a duplicate item in the set.

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])

Remove an item from the set (method 1):


set_variable.remove(item)

Note:

→if the item does not exist, it will show / throw an error (KeyError).

Remove an item from the set (method 2):


set_variable.discard(item)

→if the item does not exist, it will not show / throw an error.

Removing the first item from the set:


deleted_item = set_variable.pop()

Deleting all the items from the set:


set_variable.clear()

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"}

# display the set


print(cities)

# Get the Length of the set


print("Total items in the set: ",len(cities))

# set traversal
print("All the cities:")
for city in cities:
print(city)

# Membership – checking if an item is a part of the set or not


item = input("Enter city to search: ")
res = item in cities
if res == True:
print(item , "found in ",cities)
else:
print(item , "not found in ",cities)

# Add an item in the set


cities.add("Kolkatta")
cities.add("Hyderabad")
cities.add("Mumbai") # we cannot add a duplicate item in the set. This line has no effect.

print(cities)

# Add Multiple Items in the set (bulk addition)


cities.update(["Chandigarh","Kanpur","Amritsar"])

print(cities)

# Remove an item from the set (method 1):


item = input("Enter city to remove: ")
cities.remove(item)

print(cities)

# Remove an item from the set (method 2):


item = input("Enter city to remove: ")
cities.discard(item)

print(cities)

# Removing the first item from the set:

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.

Tuple declaration (Empty):


tuple_variable = ()

Tuple declaration & initialization:


tuple_variable = (value1, value2, valu3, … , value_n)

Retrieve a single Tuple Item:


tuple_variable[index]

Note: cannot access a tuple beyond its size. IndexError: tuple index out of range.

Get the Length of the tuple:


len(tuple_variable)

Tuple Traversal – method 1 (syntax):


for index_variable in range(0, len(tuple_variable)):
tuple_variable[index_variable]

Tuple Traversal – using the foreach loop - method 2 (syntax):


for temp_variable in tuple_variable:
temp_variable

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)

Get Min tuple item:


Note: this will only work if all the tuple items belong to the same data type.

result_variable = min(tuple_variable)

Tuple Operations:

Comparing two tuples using ==


boolean_result_variable = tuple_variable1 == tuple_variable2

Note:

→if tuple_variable1 is same as tuple_variable2 → we get True in the boolean_result_variable.

→if tuple_variable1 is not same as tuple_variable2 → we get False in the boolean_result_variable.

Comparing two tuples using >


boolean_result_variable = tuple_variable1 > tuple_variable2

Note:

→if tuple_variable1 is greater than tuple_variable2 → we get True in the boolean_result_variable.

→if tuple_variable1 is less than tuple_variable2 → we get False in the boolean_result_variable.

Comparing two tuples using <


boolean_result_variable = tuple_variable1 < tuple_variable2

Note:

→if tuple_variable1 is less than tuple_variable2 → we get True in the boolean_result_variable.

→if tuple_variable1 is greater than tuple_variable2 → we get False in the boolean_result_variable.

https://nict.edu.in
5. Collections - Siddharth Arora Page 47 of 53
Convert a list to a tuple:
result_tuple_variable = tuple(list_variable)

Convert a tuple to a list:


result_list_variable = list(tuple_variable)

https://nict.edu.in
5. Collections - Siddharth Arora Page 48 of 53
Example:
# Tuple declaration & initialization

cities = ("New Delhi","Mumbai","Chennai","Kolkatta","Bengaluru")

# Empty Tuple declaration

friends = ()

# display the tuple

print(cities)

print(friends)

# Retrieve a single Tuple Item

print("First City: ",cities[0])

# print("Tenth City: ",cities[10]) # error

# modifying tuple item:

# cities[1] = "Chandigarh" # error - TypeError: 'tuple' object does not support item assignment

# Get the Length of the tuple

print("Total items: ",len(cities))

# Tuple Traversal – method 1 (syntax):

print("Tuple Traversal – method 1 (syntax):")

for i in range(0, len(cities)):

print(cities[i])

# Tuple Traversal – using the foreach loop - method 2 (syntax):

print("Tuple Traversal – using the foreach loop - method 2 (syntax):")

for city in cities:

print(city)

https://nict.edu.in
5. Collections - Siddharth Arora Page 49 of 53
# tuple declaration

tup1 = (10, 2, 30, 4, 50 , 6)

print(tup1)

# Get Max tuple item

maxitem = max(tup1)

print("Max item: ",maxitem)

# Get Min tuple item

minitem = min(tup1)

print("Min item: ",minitem)

# tuples declaration

tup1 = (10,20,30)

tup2 = (10,25,30)

# Comparing two tuples using ==

if tup1 == tup2:

print(tup1," is equal to ",tup2)

else:

print(tup1," is not equal to ",tup2)

# Comparing two tuples using >

if tup1 > tup2:

print(tup1," is greater than ",tup2)

else:

print(tup1," is less than ",tup2)

# Convert a list to a tuple:

# 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)

# Convert a tuple to a list

tup1 = (112, 223, 334)

list1 = list(tup1)

print(tup1)

print(list1)

# create a dictionary

dict1 = dict(a=10, b=20, c=30)

print(dict1)

dict2 = dict(fname="Jaiveer", lname="Vardhan", age=14, height=172.5)

print(dict2)

https://nict.edu.in
5. Collections - Siddharth Arora Page 51 of 53
Packing and Unpacking a Tuple:
Tuple Packing:

->We can create a tuple without parentheses (brackets).

->Syntax:

tuple_variable = value1, value2, value3, value4, …. , valuen

Tuple Unpacking:

->We can assign tuple values to a sequence of regular variable.

->Syntax:

variable1, variable2, variable3, … , variablen = tuple_variable

Note: number of variables must be equal to the length of the tuple.

ValueError: too many values to unpack

ValueError: not enough values to unpack

https://nict.edu.in
5. Collections - Siddharth Arora Page 52 of 53
Example:

# tuple packing and unpacking

# 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

You might also like