Programming and Problem Solving With Python
Programming and Problem Solving With Python
WITH PYTHON
CHAPTER 11
TUPLES, SETS AND
DICTIONARIES
Introduction to Tuples
Tuples contains a sequence of items of any types.
The elements of tuples are fixed.
Tuples are immutable, i.e. once created it cannot
be changed.
In order to create a tuple the elements of tuples
are enclosed in parenthesis instead of square
bracket.
Example:
T1 = () #Creates an Empty Tuple
T2 = (12,34,56,90) #Create Tuple with 4 elements
T3 = ('a','b','c','d','e') #Create Tuple of 5
characters
T4 = 1,2,3,4,5 #Create Tuple without parenthesis
Built-in functions for Tuples
Built-in Meaning
Functions
len() Returns the number of elements in the tuple.
>>> a[4]
'O'
>>> a[-4]
'E'
Tuples are immutable
>>> t=(['A','B'],['C','D'])
>>> type(t)
<class 'tuple'>
>>> t[0]=['x','Y']
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
t[0]=['x','Y']
TypeError: 'tuple' object does not support item assignment
The + and * operator on Tuples
>>> create_tup(1,2,3,4)
(1, 2, 3, 4)
>>> create_tup('a','b')
('a', 'b')
Sorting elements of Tuple
Example:
>>> t=(76,45,23,11) #Tuple
>>> t=list(t) #Converted Tuple to a List
>>> t.sort() #Sort method of List
>>> tuple(t) #Converting List to tuple
(11, 23, 45, 76)
Zip() function
Example:
>>> t1=('Z','Y',',X')
>>> t2 =(26, 25, 24)
>>> zip(t1,t2)
[('Z', 26), ('Y', 25), (',X', 24)]
Introduction to sets
Set is an unordered collection of elements.
It is a collection of unique elements.
Duplication of elements is not allowed.
Sets are mutable so we can easily add or remove elements.
A programmer can create a set by enclosing the elements
inside a pair of curly braces i.e. {}.
The elements within the set are separated by commas.
The set can be created by the in built set() function.
Example:
>>> s2 = {1,2,3,4,5}
>>> s2
{1, 2, 3, 4, 5}
>>> type(s2)
<class 'set'>
Methods of Set Class
Function Meaning
• s.add(x)
Add element x to existing set s.
Example:
>>> A = {1,2,3,4}
>>> B = {2,5,6,7,9}
>>> A.difference(B)
{1, 3, 2}
Example:
>>> A = {1,2,3,4}
>>> B = {2,5,6,7,9}
>>> A.symmetric_difference(B)
{1,3,4,5,6,7,9}
To add new item to a dictionary you can use the subscript [] operator.
Syntax:
Dictionary_Name[key] = value
Example:
>>> D={'Virat Kohli':52,'Sachin':100}
>>> D
{'Sachin': 100, 'Virat Kohli': 52}
>>> type(D)
<class 'dict'>
>>> D['Dhoni']=28 #Adding New value to D
>>> D
{'Sachin': 100, 'Dhoni': 28, 'Virat Kohli': 52}
Deleting Entries from Dictionaries
The del operator is used to remove the key and its associated
value.
Syntax
del dictionary_name[key]
Example:
>>> D={'Virat Kohli':52,'Sachin':100, 'Dhoni': 28}
>>> D
{'Sachin': 100, 'Dhoni': 28, 'Virat Kohli': 52}
>>> del D['Dhoni'] #Deleting one entry
>>> D
{'Sachin': 100, 'Virat Kohli': 52}
The Methods of Dictionary Class
Methods of dict Class What it does?
Output: