0% found this document useful (0 votes)
2 views45 pages

Python Dictionaries and Tuples Guide

Uploaded by

pavanbeemeneni
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)
2 views45 pages

Python Dictionaries and Tuples Guide

Uploaded by

pavanbeemeneni
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

UNIT -III

Dictionaries: Creating Dictionary, Accessing and Modifying key:value Pairs in Dictionaries, BuiltIn Functions Used
on Dictionaries, Dictionary Methods, del Statement.
Tuples and Sets: Creating Tuples, Basic Tuple Operations, tuple() Function, Indexing and Slicing in Tuples, Built-In
Functions Used on Tuples, Relation between Tuples and Lists, Relation between Tuples and Dictionaries, Using zip()
Function, Sets, Set Methods, Frozenset.
Sample Experiments:
13. Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
14. Write a program to count the number of vowels in a string (No control flow allowed).
15. Write a program to check if a given key exists in a dictionary or not.
16. Write a program to add a new key-value pair to an existing dictionary.
17. Write a program to sum all the items in a given dictionary

PYTHON DICTIONARY
➢ It is one of the most important concept in python programming language
➢ Dictionaries are mutable values, it means we can add, delete, update the values according to our
requirement
➢ Values are not stored in sequence order
➢ Dictionary contains two values key and value ,which is separate by ‘:’
➢ Dictionaries created by using curly braces {}.
➢ In Dictionary keys are always unique and values might be can repeated.
➢ We can traverse the dictionary by using the key using easily.
SYNATAX:
Dictionary_Name={‘key1′:value1,’key2′:value2,’key3′:value3,’key4′:value4 ……………’keyn’:valuen}
ACCESS THE DICTIONARY:
Dictionary_Name[‘key1’]
Dictionary_Name[‘key2’]
………………………………….
…………………………………
………………………………….
Dictionary_Name[‘keyn’]

Note: We can create the empty dictionary also


Dictionary_Name={}

EXAMPLE:

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 1
phone_book={
'ramu':'1234568790',
'ramya':'9865321478',
'santhosh':'9325698789',
'ajay':'6326598752',
'vinod':'9862365981'
}
print ("phone number:",phone_book['ramu'])
print ("phone number:",phone_book['ramya'])
print ("phone number:",phone_book['santhosh'])
print ("phone number:",phone_book['ajay'])
print ("phone number:",phone_book['vinod'])
OUTPUT:
phone number: 1234568790
phone number: 9865321478
phone number: 9325698789
phone number: 6326598752
phone number: 9862365981
➢ The above example is creating the dictionary of 5 elements. In each element first string is a key and
second string is value i.e. ramu is the key for the value of 1234567890,so rest of all also created in
same manner
➢ We can create the dictionary by using predefined method “dict()”,by using this method we can
create the dictionary. But here we can’t use like key and pairs, we can pass the keyword arguments.
SYNTAX:
Dictionary_Name=dict()
EXAMPLE:
phone_book=dict(
ramu='1234568790',
ramya='9865321478',
santhosh='9325698789',
ajay='6326598752',
vinod='9862365981'
)
print ("phone number:",phone_book['ramu'])
print ("phone number:",phone_book['ramya'])
print ("phone number:",phone_book['santhosh'])
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 2
print ("phone number:",phone_book['ajay'])
print ("phone number:",phone_book['vinod'])
OUTPUT:
phone number: 1234568790
phone number: 9865321478
phone number: 9325698789
phone number: 6326598752
phone number: 9862365981
If particular key not found in dictionary then it throughs the error is as ‘Keyerror’
Traceback (most recent call last):
File “[Link]”, line 12, in <module>
print (“phone number:”,phone_book[‘vnod’])
KeyError: ‘vnod’
We can create the dictionary combination of multiple data type’s string, integers, floats etc.
EXAMPLE:
combine_dict={
'fruit':'Apple',
'contact':9865485231,
'fees':52426.365,
'complex':4+1j
}
print ("fruit is:",combine_dict['fruit'])
print ("contact is:",combine_dict['contact'])
print ("fees is:",combine_dict['fees'])
print ("complex is:",combine_dict['complex'])
OUTPUT:
contact is: 9865485231
fees is: 52426.365
complex is: (4+1j)
ADD, UPDATE AND DELETE The Elements in The Existing Dictionary
ADD: We add the new element to the already existing dictionary
SYNTAX:
dictionary_name[‘Nekey’]=value
UPDATE: We can update already existing element to the already existing dictionary

SYNTAX:
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 3
dictionary_name[‘existing_key’]=value
DELETE: By using delete we can delete individual element from the dictionary
SYNTAX:
del dictionary_name[‘existingkey’]
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("Before modifyiing the details")
print ("*********************************")
print ("Name is:",student_details['name'])
print ("Skill is:",student_details['skill'])
print ("Contact is:",student_details['contact'])
print ("Skill is:",student_details['earns'])
print ("Address is:",student_details['Address'])
print ("*********************************")
student_details['BloodGroup']="B+"
print ("After adding the new element to the dictionary")
print ("*********************************")
print ("Name is:",student_details['name'])
print ("Skill is:",student_details['skill'])
print ("Contact is:",student_details['contact'])
print ("Skill is:",student_details['earns'])
print ("Address is:",student_details['Address'])
print ("Blood Group is:",student_details['BloodGroup'])
print ("*********************************")
student_details['skill']="C"
print ("After update the exist element to the dictionary")
print ("*********************************")
print ("Name is:",student_details['name'])
print ("Skill is:",student_details['skill'])
print ("Contact is:",student_details['contact'])
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 4
print ("Skill is:",student_details['earns'])
print ("Address is:",student_details['Address'])
print ("Blood Group is:",student_details['BloodGroup'])
print ("*********************************")
del student_details['skill']
print ("After delete the element dictionary")
print ("*********************************")
print ("Name is:",student_details['name'])
print ("Contact is:",student_details['contact'])
print ("Skill is:",student_details['earns'])
print ("Address is:",student_details['Address'])
print ("Blood Group is:",student_details['BloodGroup'])
print ("Skill is:",student_details['skill'])
print ("*********************************")
OUTPUT:
Before modifyiing the details
*********************************
Name is: samad
Skill is: Python
Contact is: 9542132140
Skill is: 5462.325
Address is: Bangalore
*********************************
After adding the new element to the dictionary
*********************************
Name is: samad
Skill is: Python
Contact is: 9542132140
Skill is: 5462.325
Address is: Bangalore
Blood Group is: B+
*********************************
After update the exist element to the dictionary
*********************************
Name is: samad
Skill is: C
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 5
Contact is: 9542132140
Skill is: 5462.325
Address is: Bangalore
Blood Group is: B+
*********************************
After delete the element dictionary
*********************************
Name is: samad
Contact is: 9542132140
Skill is: 5462.325
Address is: Bangalore
Blood Group is: B+
Traceback (most recent call last):
File "[Link]", line 47, in <module>
print ("Skill is:",student_details['skill'])
KeyError: 'skill'
CLEAR: clear is method to delete the all elements in the dictionary
SYNTAX:
dictionary_name.clear()
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("Before delete the details")

print ("*********************************")
print ("Name is:",student_details['name'])
print ("Skill is:",student_details['skill'])
print ("Contact is:",student_details['contact'])
print ("Skill is:",student_details['earns'])
print ("Address is:",student_details['Address'])
print ("*********************************")
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 6
student_details.clear()
print ("After delete the details")
print ("*********************************")
print ("Name is:",student_details['name'])
print ("Skill is:",student_details['skill'])
print ("Contact is:",student_details['contact'])
print ("Skill is:",student_details['earns'])
print ("Address is:",student_details['Address'])
print ("*********************************")
OUTPUT:
Before delete the details
*********************************
Name is: samad
Skill is: Python
Contact is: 9542132140
Skill is: 5462.325
Address is: Bangalore
After delete the details
*********************************
Traceback (most recent call last):
File "[Link]", line 19, in <module>
print ("Name is:",student_details['name'])
KeyError: 'name<strong>'</strong>
LEN METHOD: This method is used to find the length of the dictionary
SYNTAX:
len(dictionary_name)
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("Length of dictionary:",len(student_details))
OUTPUT:
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 7
Length of dictionary: 5

ITERATE THE DICTIONARY BY USING THE KEYS.


EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
for key in student_details:
print(key," is :",student_details[key])
OUTPUT:
skill is : Python
name is : samad
Address is : Bangalore
earns is : 5462.325
contact is : 9542132140
MEMBERSHIP OPERATOR:
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("is skill in dictionary:","skill" in student_details)
print ("is earns in dictionary:","earns" in student_details)
print ("is fruit not in dictionary:","fruit" not in student_details)
print ("is money in dictionary:","money" in student_details)
OUTPUT:
is skill in dictionary: True
is earns in dictionary: True
is fruit not in dictionary: True
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 8
is money in dictionary: False
RELATION OPERATORS WITH DICTIONARY
We can compare the two dictionaries by using relational operator
EXAMPLE:
dict1={'idly':20,'dosa':50,}
dict2={'dosa':50, 'idly':20}
print ("Both are same:",dict1==dict2)
print ("Both are same:",dict1!=dict2)
OUTPUT:
Both are same: True
Both are same: False
KEYS METHOD:
To extract the keys we can use keys method
SYNTAX:
dictionary_name.keys()
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("Keys are:",student_details.keys())
OUTPUT:
Keys are: ['skill', 'contact', 'earns', 'name', 'Address']
VALUES METHOD: To extract the values we can use keys method
SYNTAX:
dictionary_name.values()
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 9
}
print ("values are:",student_details.values())
OUTPUT:
values are: ['Python', 9542132140L, 5462.325, 'samad', 'Bangalore']
ITEMS METHOD: It will return the sequence of tuples,in each tuple key and value will contain
SYNTAX:
dictionary_name.items()
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("tuples are:",student_details.items())
OUTPUT:
tuples are: [('skill', 'Python'), ('contact', 9542132140L),
('earns', 5462.325), ('name', 'samad'), ('Address', 'Bangalore')]
GET METHOD:
Get method also one of the method to get the specific value by using key, while get we found specific in
dictionary then it will return the value or else it will return the None, But when we are using key we can
mention the default statement also.
SYNTAX:
dictionary_name.get(key,[default])
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("value:",student_details.get('name'))
print ("value at:",student_details.get('fruit'))
print ("value at:",student_details.get('fruit',"Oh!!Not Found"))
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 10
OUTPUT:
value: samad
value at: None
value at: Oh!!Not Found
POP METHOD: pop method is used delete the particular element by using the key.
SYNTAX:
dictionary_name.pop(‘existingkey’)
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("value:",student_details.pop('name'))
print ("value:",student_details.pop('name'))
OUTPUT:
value: samad
Traceback (most recent call last):
File "[Link]", line 9, in <module>
print ("value:",student_details.pop('name'))
KeyError: 'name'
POPITEM METHOD: This method delete the random elements and return thet element
SYNTAX:
dictionary_name.popitem()
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
print ("value:",student_details.popitem())
OUTPUT:
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 11
value: ('contact', 9542132140)
Note: It will delete and returns the random value
COPY METHOD: it will create the new dictionary
SYNTAX:
copy_dictionary_name=dictionary_name.copy()
EXAMPLE:
student_details={
'name':'samad',
'skill':'Python',
'contact':9542132140,
'earns':5462.325,
'Address':'Bangalore'
}
copy_student_details=student_details.copy()
print ("After copied the details")
print ("*********************************")
print ("Name is:",copy_student_details['name'])
print ("Skill is:",copy_student_details['skill'])
print ("Contact is:",copy_student_details['contact'])
print ("Skill is:",copy_student_details['earns'])
print ("Address is:",copy_student_details['Address'])
print ("*********************************")
OUTPUT:
After copied the details
*********************************
Name is: samad
Skill is: Python
Contact is: 9542132140
Skill is: 5462.325
Address is: Bangalore
Python Del Keyword

The del keyword in Python is used to delete objects like variables, lists, dictionary entries, or slices of a
list. Since everything in Python is an object, del helps remove references to these objects and can free up
memory

del Keyword removes the reference to an object. If that object has no other references, it gets cleared from
memory. Trying to access a deleted variable or object will raise a NameError.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 12
Syntax

del object_name

object_name: name of the object to delete (list, set dictionary, etc).

Del Keyword for Deleting Objects

In the example below, we will delete Gfg_class using del statement.

class Gfg_class:
a = 20
# creating instance of class
obj = Gfg_class()
# delete object
del obj
# we can also delete class
del Gfg_class
Deleting Variables
del keyword can be used to delete variables too.
a = 20
b = "Python Programming"
# delete both the variables
del a, b
# check if a and b exists after deleting
print(a)
print(b)
output
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[2], line 8
5 del a, b
7 # check if a and b exists after deleting
----> 8 print(a)
9 print(b)
NameError: name 'a' is not defined
Explanation: del a, b removes the existence of a and b therefore print() function is not able to find them.

List Slicing Using del Keyword


In the program below we will delete some parts of a list (basically slice the list) using del keyword.
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 13
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] output
# delete second element of 'a' [1, 3, 4, 5, 6, 7, 8, 9]
del a[1] [1, 3, 4, 7, 8, 9]
# check if the second element in 'a' is deleted
print(a)
# slice 'a' from index 3 to 5
del a[3:5]
# check if the elements from index 3 to 5 in 'a' is deleted
print(a)

Deleting Dictionary and Removing key-value Pairs


In the program below we will remove few key-value pairs from a dictionary using del keyword.
d = {"small": "big", "black": "white", "up": "down"} OUTPUT
# delete key-value pair with key "black" from my_dict1 {'small': 'big', 'up': 'down'}
del d["black"]
# check if the key-value pair with key "black" from d1 is deleted
print(d)

Python delattr() Function


In Python, the delattr() function is used to delete an attribute from an object.
Python delattr() Syntax
delattr (object, name)
Parameters:
Object: An object from which we want to delete the attribute
name: The name of the attribute we want to delete
The delattr() method returns a complex number.
delattr() Function in Python
Python delattr() Function is used to delete an object attribute in Python. It takes two arguments, the first
one is the class object from which we want to delete, second is the name of the attribute which we want to
delete. We can use delattr() to remove an attribute dynamically at runtime in Python.

How does delattr() works?

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 14
class Equation: Output
x=3 Value of x = 3
y = -8 Value of y = -8
z=5 Value of z = 5
l1 = Equation() Value of x = 3
print("Value of x = ", l1.x) ERROR!
print("Value of y = ", l1.y) Traceback (most recent call last):
print ("Value of z = ", l1.z) File "<string>", line 14, in <module>
delattr(Equation,'z') AttributeError: 'Equation' object has no attribute 'z'
print ("Value of x = ", l1.x)
print ("Value of y = ", l1.z)

Python delattr() Examples


Example 1
A class course is created with attributes name, duration, price, rating. An instance of the class is
created and now we delete the rating attribute using delattr() method. Finally, we check if
the rating attribute is present or not. A try block is used to handle the keyError
class course: Output
name = "data structures using python" 5
duration_months = 6 type object 'course' has no attribute
price = 20000 'rating'
rating = 5
# creating an object of course
print([Link])
# deleting the rating attribute from object
delattr(course, 'rating')
# checking if the rating attribute is there or not
try:
print([Link])
except Exception as e:
print(e)

PYTHON TUPLE
➢ Python tuple is an immutable object, it is combination of homogeneous or heterogeneous data types
➢ To access the elements in tuple we can use index, which start from 0 and stop with n-1
➢ In tuple elements are stored in sequence manner
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 15
➢ In tuple every element is separated by comma
➢ We can create empty tuple also in python.
➢ In tuple elements are enclosed in parenthesis “()”
DIFFERENT TYPES OF SYNTAX:
CREATING EMPTY TUPLE:
SYNTAX: tuple=()
Note: It will create empty tuple
CREATE TUPLE WITH DATA:
SYNTAX: tuple_name=(data1,data2,data3……….datan)
How print the complete tuple:
EXAMPLE:
custom_tuple=(1,2,3,4,5)
print (custom_tuple)
OUTPUT:
(1, 2, 3, 4, 5)
How to access the tuple elements:
To access the elements in tuple there two tw type of indexing is available.
➢ [Link] Indexing
➢ [Link] Indexing
[Link] INDEXING:
The starting index ( mostly ‘0 ‘ ) is positive and ending index (n-1) is also positive then we can call
it as Forward Indexing i.e almost it is in ascending order .i.e. consist tuple having an elements are
0,1,2,3,4,5
my_tuple=(0,1,2,3,4,5)
In this case start index is ‘0’ and end index is ‘6’
my_tuple[0] is 0
my_tuple[1] is 1
my_tuple[2] is 2
my_tuple[3] is 3
my_tuple[4] is 4
my_tuple[5] is 5
Below is the example is illustrating accessing the tuple elements for different data types.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 16
Example:
tup = (1,2,3,4,5,6,7)
print(tup[0])
print(tup[1])
print(tup[2])
# It will give the IndexError
print(tup[8])
Output:
1
2
3
tuple index out of range
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an element outside of
tuple that raised an Index Error.
HOW TO SLICE THE ELEMENT IN TUPLE:
Tuple slice can be used slice particular part of the tuple and as well as to modify the particular part
of the tuple we can use the slice mechanism in tuple
EXAMPLE:
tuple1=(9,6,5,8,1,3,7,4)
print (tuple1) #printing the complete tuple
print (tuple1[:-5]) #This will slice the elements from -5 to backward index
print (tuple1[-5:]) #This will slice the elements from -5 to forward index
print (tuple1[:5]) #This will slice the elements from 5 to backward index
print (tuple1[5:]) #This will slice the elements from 5 to forward index
print (tuple1[2:5]) #This willslice the elements in between 2:5
OUTPUT:
(9, 6, 5, 8, 1, 3, 7, 4)
(9, 6, 5)

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 17
(8, 1, 3, 7, 4)
(9, 6, 5, 8, 1)
(3, 7, 4)
(5, 8, 1)
Tuple slicing in forward indexing
tuple = (1,2,3,4,5,6,7)
#element 1 to end
print(tuple[1:])
#element 0 to 3 element
print(tuple[:4])
#element 1 to 4 element
print(tuple[1:5])
# element 0 to 6 and take step of 2
print(tuple[0:6:2])
Output:
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)
2. BACKWARD INDEXING (or)NEGATIVE INDEXING:
The starting index ( mostly ‘-n’ ) is negative number and ending index (-n+(n-1)) is also negative
number then we can call it as Backward Indexing i.e consider tuple having an elements are 1,2,3,4,5,6,7 i.e
here no. of elements are 7 so starting index (-n) means -7 and ending index means (-n+(n-1)) -1
my_tuple=[1,2,3,4,5]
In this case start index is ‘0’ and end index is ‘6’
my_tuple[-5] is 1
my_tuple[-4] is 2
my_tuple[-3] is 3
my_tuple[-2] is 4
my_tuple[-1] is 5
Below is the example is illustrating accessing the tuple elements for different data types.
Example
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
print(tuple1[-3:-1])
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 18
print(tuple1[:-1])
print(tuple1[-2:])
Output:
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)
CHANGING A TUPLE
➢ Unlike lists, tuples are immutable.
➢ This means that elements of a tuple cannot be changed once they have been assigned. But, if the
element is itself a mutable data type like list, its nested items can be changed.
➢ We can also assign a tuple to different values (reassignment).
# Changing tuple values Example
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][0] = 9
print(my_tuple)
my_tuple = ('j', 'u', 's', 't', 'd', 'o', 'i', 't',)
print(my_tuple)
Output
(4, 2, 3, [9, 5])
('j', 'u', 's', 't', 'd', 'o', 'i', 't')
➢ We can use + operator to combine two tuples. This is called concatenation.
➢ We can also repeat the elements in a tuple for a given number of times using the * operator.
➢ Both + and * operations result in a new tuple.
Concatenation
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Output
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
DELETING A TUPLE
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or
remove items from a tuple.
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 19
Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples
my_tuple = ('j', 'u', 's', 't', 'd', 'o', 'i', 't')
del my_tuple
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]
# Can delete an entire tuple
# NameError: name 'my_tuple' is not defined
print(my_tuple)
Output
Traceback (most recent call last):
File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined
ITERATING THROUGH A TUPLE
We can use a for loop to iterate through each item in a tuple.
# Using a for loop to iterate through a tuple
for name in ('John', 'Kate'):
print("Hello", name)
Output
Hello John
Hello KateLoop Through a Tuple
You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
output
apple
banana
cherry
How to find the tuple length
To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 20
tuple = ("apple", "banana", "cherry")
print(len(tuple))
output: 3
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
tuple = ("apple", "banana", "cherry")
if "apple" in tuple:
print("Yes, 'apple' is in the fruits tuple")
Output
Yes, 'apple' is in the fruits tuple
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
tuple = ("apple", "banana", "cherry")
tuple[3] = "orange" # This will raise an error
print(tuple)
Output
Traceback (most recent call last):
File "C:/Users/BHANU/Documents/Bhanu python/[Link]", line 2, in <module>
thistuple[3] = "orange" # This will raise an error
TypeError: 'tuple' object does not support item assignment
REMOVE ITEMS
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
Output
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
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 21
NameError: name 'thistuple' is not defined
HOW TO JOIN TWO TUPLES
To join two or more tuples you can use the + operator:
Example
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output
('a', 'b', 'c', 1, 2, 3)
THE TUPLE () CONSTRUCTOR
It is also possible to use the tuple () constructor to make a tuple.
Example
Using the tuple () method to make a tuple:
thistuple = tuple (("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Output
('apple', 'banana', 'cherry')
HOW TO REPLICATE THE PYTHON TUPLE:
Here Replicate means adding the same tuple multiple time wit all elements, we can achieve this
mechanism by using ateristic symbol (‘*’)
EXAMPLE:
tuple =(1,2,3)
print (tuple*1) #No replication
print (tuple*2) #one time replication
print (tuple*3) #two time replication
print (tuple*4) #three time replication
OUTPUT:
(1, 2, 3)
(1, 2, 3, 1, 2, 3)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
UPDATE TUPLE:
We should not update the tuple because of it is immutable, it means it is having the constant values

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 22
del method:
We delete the complete tuple, but we can’t delete the specific or individual elements in tuple by using
delete method.
SYNTAX:
del(index) Note: Here index might be a single value ,slice of tuple also we can use
EXAMPLE:
tuple = ("xyz", 420, 99.90)# tuple with the name number and marks
print ("tuple before delete operator:", tuple)
del tuple
print ("tupes is not avilable:", tuple)
OUTPUT:
tuple before delete operator: ('xyz', 420, 99.9)
tupes is not avilable: <class 'tuple'>
TUPLE METHODS
Methods that add items or remove items are not available with tuple. Only the following two methods are
available.
Python has two built-in methods that you can use on tuples.
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
Examples
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p'))
print(my_tuple.index('l'))
Output
2
3
MAX, MIN, COUNT, LEN AND SUM METHODS:
MAX METHOD: This Method is used to find the biggest element in the tuple.
MIN METHOD: This Method is used to find the smallest element in the tuple.
COUNT METHOD: This Method is used to count the occurrence of specific element in the tuple.
LEN METHOD: This Method is used to count the total elements in the tuple.
SUM METHOD: This Method is used find the sum of the elements in the tuple.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 23
EXAMPLE:
tuple=(100,269,32,269,1000,21)
print ("Biggest element in tuple:",max(tuple))
print ("Smallest element in tuple:",min(tuple))
print ("sum of elements in tuple:",sum(tuple))
print ("count the number of elements in tuple:",len(tuple))
print ("count the element occurance [Link] times:",[Link](269))
OUTPUT:
Biggest element in tuple: 1000
Smallest element in tuple: 21
sum of elements in tuple: 1691
count the number of elements in tuple: 6
count the element occurance [Link] times: 2
BASIC TUPLE OPERATIONS
➢ The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they
work with the list. Consider the following table for more detail.
➢ Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.
Operator Description Example
Repetition The repetition operator enables the tuple elements to T1*2 = (1, 2, 3, 4, 5, 1,
be repeated multiple times. 2, 3, 4, 5)
Concatenation It concatenates the tuple mentioned on either side of T1+T2 = (1, 2, 3, 4, 5,
the operator. 6, 7, 8, 9)
Membership It returns true if a particular item exists in the tuple print (2 in T1) prints
otherwise false True.
Iteration The for loop is used to iterate over the tuple elements. for i in T1:
print(i)
Output
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 24
PYTHON TUPLE INBUILT FUNCTIONS
SN Function Description
1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.

WHERE USE TUPLE?


Using tuple instead of list is used in the following scenario.
1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be changed.
2. Tuple can simulate a dictionary without keys. Consider the following nested structure, which can be used
as a dictionary.
[(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]
ADVANTAGES OF TUPLE OVER LIST
➢ Since tuples are quite similar to lists, both of them are used in similar situations. However, there are
certain advantages of implementing a tuple over a list. Below listed are some of the main
advantages:
➢ We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar)
data types.
➢ Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight
performance boost.
➢ Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not
possible.
➢ If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.
DIFFERENCE BETWEEN LIST AND TUPLE
List and Tuple in Python are the class of data structure. The list is dynamic, whereas tuple has static
characteristics.
List are just like the arrays, declared in other languages. Lists need not be homogeneous always
which makes it a most powerful tool in Python.
In Python, the list is a type of container in Data Structures, which is used to store multiple data at
the same time. Lists are a useful tool for preserving a sequence of data and further iterating over it.
Syntax:
list_data = ['an', 'example', 'of', 'a', 'list']

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 25
Tuple is also a sequence data type that can contain elements of different data types, but these are
immutable in nature. In other words, a tuple is a collection of Python objects separated by commas. The
tuple is faster than the list because of static in nature.
Syntax:
tuple_data = ('this', 'is', 'an', 'example', 'of', 'tuple')
SN List Tuple
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has a variable length. The tuple has the fixed length.
4 The list provides more functionality than a tuple. The tuple provides less functionality than the list.
5 The list is used in the scenario in which we need The tuple is used in the cases where we need to store the
to store the simple collections with no constraints read-only collections i.e., the value of the items cannot be
where the value of the items can be changed. changed. It can be used as the key inside the dictionary.
6 The lists are less memory efficient than a tuple. The tuples are more memory efficient because of its

Comparing Tuple and Dictionary


The difference between a tuple and a dictionary in Python lies in how they store and retrieve data.
We can access the elements of a tuple using an index, while we can access the elements of a dictionary
using keys.
Example
We have declared a tuple called 'names' and a dictionary called 'designation'. We will access the
first name from the tuple using the index value and the designation of that employee using a key.
# Tuple example Output
names = ("Amit", "Ankit", "Aakriti") First name in tuple: Amit
# Access by index Employee Designation: Trainee
print("First name in tuple:", names[0]) Engineer
# Dictionary example
designation = {
"Amit": "Trainee Engineer",
"Ankit": "Project Manager",
"Aakriti": "Technical Lead"
}
# Access by key
print("Employee Designation:", designation[names[0]])

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 26
Differences between a tuple and a dictionary
Tuple Dictionary
A tuple is a non-homogeneous data structure that Dictionary is a non-homogeneous data structure
can hold a single row as well as several rows and that contains key-value pairs.
columns.
Tuples are represented by brackets (). Dictionaries are represented by curly brackets {}.
Tuples are immutable, i.e, we cannot make Dictionaries are mutable, and keys do not allow
changes. duplicates.
A tuple is ordered. Dictionary is ordered (Python 3.7 and above).
A tuple can be created using the tuple () function. Dictionary can be created using the dict()
function.
Creating an empty Tuple: () Creating an empty dictionary: {}
As tuples are immutable, the reverse() method is Because the dictionary's entries are in the form of
not defined in them. key-value pairs, the elements cannot be reversed.
Example: ('python', 'simple', 'easy to understand) Example: {'companyname': 'python', 'tagline':
'easy to under stand'}

Zip () in Python
The zip() function in Python combines multiple iterables such as lists, tuples, strings, dict etc,
into a single iterator of tuples. Each tuple contains elements from the input iterables that are at the same
position.
names = ['John', 'Alice', 'Bob', 'Lucy'] Output
scores = [85, 90, 78, 92] [('John', 85), ('Alice', 90), ('Bob', 78), ('Lucy', 92)]
res = zip(names, scores)
print(list(res))
Explanation:
➢ zip() is used to combine the two lists into a single iterable 'res'
➢ Each element from names is paired with the corresponding element from scores
➢ list() converts the iterator from zip() into a list of tuples, making it easier to visualize or manipulate the
combined data.
Syntax of zip()
zip(*iterables)
Parameters:
*iterables refers to one or more iterable objects (like lists, tuples, etc.) that we want to combine. The
function pairs elements from these iterables into tuples based on their positions.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 27
Return value:
Returns an iterator of tuples, where each tuple contains elements from the input iterables at the same index.
If the input iterables are of unequal length then zip() stops creating tuples when the shortest iterable is
exhausted.
Key Points:
• If no parameters are passed, zip() returns an empty iterator.
• If only one iterable is passed, the result will be a series of single-element tuples.
• If multiple iterables are passed, each tuple will contain one element from each iterable.
Examples of zip()
Below example shows how zip() works when no parameter, one and two iterable are passed into parameter.
a = [1, 2, 3] Output
b = ['a', 'b', 'c'] []
# No iterable are passed [(1,), (2,), (3,)]
res = zip() [(1, 'a'), (2, 'b'), (3, 'c')]
# Converting iterator to list
print(list(res))
# One iterable is passed
res = zip(a)
# Converting iterator to list
print(list(res))
# Two iterables are passed
res = zip(a, b)
# Converting iterator to list
print(list(res))
Iterables of different Lengths
When using iterables of different lengths, the zip() will only pair up to the shortest iterable.
names = ['Alice', 'Bob', 'Charlie'] Output
scores = [88, 94] [('Alice', 88), ('Bob', 94)]
res = zip(names, scores)
print(list(res))
Explanation: Here, zip() stops after pairing the two available score values with the first two name values.
'Charlie' is left out since there’s no corresponding score value.
Unzipping data with zip()
We can also reverse the operation by unzipping the data using the * operator.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 28
a = [('Apple', 10), ('Banana', 20), ('Orange', 30)] Output
fruits, quantities = zip(*a) Fruits: ('Apple', 'Banana', 'Orange')
print(f"Fruits: {fruits}") Quantities: (10, 20, 30)
print(f"Quantities: {quantities}")

Explanation: Using the * operator, we can separates (unzip) the paired fruit names and their quantities
back into their respective sequences
Combine dictionary keys and values
We can use zip() to combine dictionary keys and values, or even iterate over multiple dictionaries
simultaneously. Here’s an example pairing dictionary keys and values.
d = {'name': 'Alice', 'age': 25, 'grade': 'A'} Output
keys = [Link]() [('name', 'Alice'), ('age', 25), ('grade', 'A')]
values = [Link]()
res = zip(keys, values)
print(list(res))

PYTHON SET
➢ A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements.
➢ Sets are mutable which means we can modify it after its creation.
➢ Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index.
➢ However, we can print them all together, or we can get the list of elements by looping through the
set.
CREATING A SET
➢ The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
➢ Python also provides the set() method, which can be used to create the set by the passed sequence.
Example 1: Using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 29
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Example 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
➢ It can contain any type of element such as integer, float, tuple etc.
➢ But mutable elements (list, dictionary, set) can't be a member of set.
Example:
# Creating a set which have immutable elements
set1 = {1,2,3, "JavaTpoint", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 30
Output:
<class 'set'>
Traceback (most recent call last)
<ipython-input-5-9605bb6fbc68> in <module>
4
5 #Creating a set which holds mutable elements
----> 6 set2 = {1,2,3,["Javatpoint",4]}
7 print(type(set2))
TypeError: unhashable type: 'list'
In the above code, we have created two sets, the set set1 have immutable elements and set2 have one
mutable element as a list. While checking the type of set2, it raised an error, which means set can contain
only immutable elements.
Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary as
well. So Python provides the set() method used without an argument to create an empty set.
Example:
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))
Output:
<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.
Example:
set5 = {1,2,4,4,5,8,9,9,10}
print("Return set with unique elements:",set5)
Output:
Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}

In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it remove
the duplicity from the set.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 31
ADDING ITEMS TO THE SET
Python provides the add() method and update() method which can be used to add some particular item to
the set. The add() method is used to add a single element whereas the update() method is used to add
multiple elements to the set.
Example: 1 - Using add() method
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(“months”)
print("\nAdding other months to the set...");
[Link]("July");
[Link] ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:
printing the original set ...
{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January
To add more than one item in the set, Python provides the update() method. It accepts iterable as an
argument.
Example - 2 Using update() function
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 32
print(Months)
print("\nupdating the original set ... ")
[Link](["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);
Output:
printing the original set ...
{'January', 'February', 'April', 'May', 'June', 'March'}
updating the original set ...
printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
REMOVING ITEMS FROM THE SET
Python provides the discard() method and remove() method which can be used to remove the items from
the set. The difference between these function, using discard() function if the item does not exist in the set
then the set remain unchanged whereas remove() method will through an error.
Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
[Link]("January");
[Link]("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
Output:
printing the original set ...
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 33
April
June
Python provides also the remove() method to remove the item from the set. Consider the following example
to remove the items using remove() method.
Example-2 Using remove() function
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
[Link]("January");
[Link]("May");
print("\nPrinting the modified set...");
print(months)
Output:
printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}
Removing some months from the set...
Printing the modified set...
{'February', 'June', 'April', 'March'}
We can also use the pop() method to remove the item. Generally, the pop() method will always remove the
last item but the set is unordered, we can't determine which element will be popped from set.
Consider the following example to remove the item from the set using pop() method.
Example:
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
[Link]();
[Link]();
print("\nPrinting the modified set...");
print(Months)
Output:
printing the original set ...
{'June', 'January', 'May', 'April', 'February', 'March'}
Removing some months from the set...
Printing the modified set...
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 34
{'May', 'April', 'February', 'March'}
In the above code, the last element of the Month set is March but the pop() method removed the June and
January because the set is unordered and the pop() method could not determine the last element of the set.
Python provides the clear() method to remove all the items from the set.
EXAMPLE.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving all the items from the set...");
[Link]()
print("\nPrinting the modified set...")
print(Months)
Output:
printing the original set ...
{'January', 'May', 'June', 'April', 'March', 'February'}
Removing all the items from the set...
Printing the modified set...
set()
DIFFERENCE BETWEEN DISCARD() AND REMOVE()
➢ Despite the fact that discard() and remove() method both perform the same task, There is one main
difference between discard() and remove().
➢ If the key to be deleted from the set using discard() doesn't exist in the set, the Python will not give
the error. The program maintains its control flow.
➢ On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the
Python will raise an error.
Example-
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving items through discard() method...");
[Link]("Feb"); #will not give an error although the key feb is not available in the
set
print("\nprinting the modified set...")
print(Months)
print("\nRemoving items through remove() method...");
[Link]("Jan") #will give an error as the key jan is not available in the set.
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 35
print("\nPrinting the modified set...")
print(Months)
Output:
printing the original set ...
{'March', 'January', 'April', 'June', 'February', 'May'}
Removing items through discard() method...
printing the modified set...
{'March', 'January', 'April', 'June', 'February', 'May'}
Removing items through remove() method...
Traceback (most recent call last):
File "[Link]", line 9, in
[Link]("Jan")
KeyError: 'Jan'
PYTHON SET OPERATIONS
Set can be performed mathematical operation such as union, intersection, difference, and symmetric
difference. Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.
Union of two Sets
The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all the
items that are present in both the sets.

Example 1: using union | operator


Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Output:
{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}
Python also provides the union() method which can also be used to calculate the union of two sets.
Example 2: using union() method
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 36
print([Link](Days2)) #printing the union of the sets
Output:
{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}
Intersection of two sets
The intersection of two sets can be performed by the and & operator or the intersection() function.
The intersection of the two sets is given as the set of the elements that common in both sets.

Example 1: Using & operator


Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
Output:
{'Monday', 'Tuesday'}
Example 2: Using intersection() method
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print([Link](set2)) #prints the intersection of the two sets
Output:
{'Martin', 'David'}
Example 3:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = [Link](set2)
print(set3)
Output:
{1,2,5}
THE INTERSECTION_UPDATE() METHOD
The intersection_update() method removes the items from the original set that are not present in both the
sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it modifies the original
set by removing the unwanted items, on the other hand, the intersection() method returns a new set.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 37
Example
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)
Output:
{'castle'}
DIFFERENCE BETWEEN THE TWO SETS
The difference of two sets can be calculated by using the subtraction (-) operator or intersection() method.
Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained
that element of A, which is not present in the set B.

Example 1 : Using subtraction ( - ) operator


Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:
{'Thursday', 'Wednesday'}
Example 2 : Using difference() method
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print([Link](Days2)) # prints the difference of the two sets Days1 and Days2
Output:
{'Thursday', 'Wednesday'}
SYMMETRIC DIFFERENCE OF TWO SETS
The symmetric difference of two sets is calculated by ^ operator or symmetric_difference() method.
Symmetric difference of sets, it removes that element which is present in both sets.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 38
Example - 1: Using ^ operator
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Example - 2: Using symmetric_difference() method
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
PYTHON SET METHODS
There are many set methods, some of which we have already used above. Here is a list of all the methods
that are available with the set objects:
METHOD DESCRIPTION
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member. (Do nothing if the
element is not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 39
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element. Raises KeyError if the
set is empty
remove() Removes an element from the set. If the element is not a member,
raises a KeyError
symmetric_difference() Returns the symmetric difference of two sets as a new set
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others

BUILT-IN FUNCTIONS WITH SET


Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used
with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as
a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
sum() Returns the sum of all elements in the set.

FROZENSETS
➢ The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set cannot be
changed and therefore it can be used as a key in the dictionary.
➢ The elements of the frozen set cannot be changed after the creation. We cannot change or append
the content of the frozen sets by using the methods like add() or remove().
➢ The frozenset() method is used to create the frozenset object. The iterable sequence is passed into
this method which is converted into the frozen set as a return type of the method.

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 40
Example
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\nprinting the content of frozen set...")
for i in Frozenset:
print(i);
[Link](6) #gives an error since we cannot change the content of Frozenset after creation
Output:
<class 'frozenset'>
printing the content of frozen set...
1
2
3
4
5
Traceback (most recent call last):
File "[Link]", line 6, in <module>
[Link](6) #gives an error since we can change the content of Frozenset after
creation
AttributeError: 'frozenset' object has no attribute 'add'
FROZENSET FOR THE DICTIONARY
If we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from the
dictionary and returns a frozenset that contains the key of the dictionary as its elements.
Example
Dictionary = {"Name":"John", "Country":"USA", "ID":101}
print(type(Dictionary))
Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary
print(type(Frozenset))
for i in Frozenset:
print(i)
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 41
Example - 1: Write a program to remove the given number from the set.
my_set = {1,2,3,4,5,6,12,24}
n = int(input("Enter the number you want to remove"))
my_set.discard(n)
print("After Removing:",my_set)
Output:
Enter the number you want to remove:12
After Removing: {1, 2, 3, 4, 5, 6, 24}
Example - 2: Write a program to add multiple elements to the set.
set1 = set([1,2,4,"John","CS"])
[Link](["Apple","Mango","Grapes"])
print(set1)
Output:
{1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'}
Example - 3: Write a program to find the union between two set.
set1 = set(["Peter","Joseph", 65,59,96])
set2 = set(["Peter",1,2,"Joseph"])
set3 = [Link](set2)
print(set3)
Output: {96, 65, 2, 'Joseph', 1, 'Peter', 59}
Example - 4: Write the program to find the issuperset, issubset and superset.
set1 = set(["Peter","James","Camroon","Ricky","Donald"])
set2 = set(["Camroon","Washington","Peter"])
set3 = set(["Peter"])
issubset = set1 >= set2
print(issubset)
issuperset = set1 <= set2
print(issuperset)
issubset = set3 <= set2
print(issubset)
issuperset = set2 >= set3
print(issuperset)
Output:
False
False
True
True
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 42
Sample Experiments:
13. Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
# Creating tuples for members
member1 = ("Rahul", 21, "Hyderabad", "AITS Tirupati")
member2 = ("Priya", 22, "Chennai", "AITS Tirupati")
# Concatenating tuples
concatenated_tuple = member1 + member2
# Printing tuples
print("Member 1 Tuple:", member1)
print("Member 2 Tuple:", member2)
print("Concatenated Tuple:", concatenated_tuple)
OUTPUT
Member 1 Tuple: ('Rahul', 21, 'Hyderabad', 'AITS Tirupati')
Member 2 Tuple: ('Priya', 22, 'Chennai', 'AITS Tirupati')
Concatenated Tuple: ('Rahul', 21, 'Hyderabad', 'AITS Tirupati', 'Priya', 22, 'Chennai', 'AITS Tirupati')

14. Write a program to count the number of vowels in a string (No control flow allowed).
# Program to count vowels without control flow
text = "Welcome to Annamacharya Institute of Technology and Sciences"
# Define vowels
vowels = "aeiouAEIOU"
# Count vowels using sum + generator expression
count = sum(map([Link], vowels))
print("Number of vowels:", count)

OUTPUT
Number of vowels: 21
➢ [Link](v) gives the count of each vowel,
➢ map([Link], vowels) maps it across all vowels,
➢ sum() adds them up.

15. Write a program to check if a given key exists in a dictionary or not.


# Program to check if a given key exists in a dictionary
student = {
"name": "Rahul",
"age": 21,
"college": "AITS Tirupati",
"branch": "CSE"

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 43
}
# Key to check
key = "college"
# Checking key existence
if key in student:
print(f"Key '{key}' exists in the dictionary with value: {student[key]}")
else:
print(f"Key '{key}' does not exist in the dictionary.")
OUTPUT
Key 'college' exists in the dictionary with value: AITS Tirupati
If you want to avoid using control flow (if), you can directly use .get():
print([Link]("college", "Key not found"))
This will print the value if the key exists, otherwise "Key not found".
Do you want me to show you both versions — with if and without if in one program?

16. Write a program to add a new key-value pair to an existing dictionary.


# Program to add a new key-value pair to an existing dictionary
student = {
"name": "Rahul",
"age": 21,
"college": "AITS Tirupati"
}
print("Original Dictionary:", student)
# Adding new key-value pair
student["branch"] = "CSE"
print("Updated Dictionary:", student)
OUTPUT
Original Dictionary: {'name': 'Rahul', 'age': 21, 'college': 'AITS Tirupati'}
Updated Dictionary: {'name': 'Rahul', 'age': 21, 'college': 'AITS Tirupati', 'branch': 'CSE'}
Alternative using update() method:
[Link]({"branch": "CSE"})
Would you like me to also show a version where the key-value pair is taken from user input instead of being
hardcoded?
17. Write a program to sum all the items in a given dictionary
# Program to sum all items in a dictionary
marks = {
"Maths": 85,
"Physics": 90,
"Chemistry": 78,
____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 44
"English": 88
}
print("Dictionary:", marks)
# Summing all values
total = sum([Link]())
print("Sum of all items in dictionary:", total)
OUTPUT
Dictionary: {'Maths': 85, 'Physics': 90, 'Chemistry': 78, 'English': 88}
Sum of all items in dictionary: 341

If you also want to sum keys + values together, you can do:
total = sum([Link]()) + sum([Link]())
Do you want me to show both sum of values only and sum of keys + values in one program?

*********************************************************************************************

____________________________________________________________________________________________
Prepared by G.S Rajitha Priya 45

You might also like