Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

Tuples, Sets and Dictionaries

Prof. Rajeev Kumar


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.

max() Returns the element with the greatest value.

min() Returns the element with the minimum value.

sum() Returns the sum of all the elements of tuple.

index(x) Returns the index of element x.


count(x) Returns the number of occurrence of element x.
Indexing, and Slicing
 The indexing and slicing of tuples is similar to lists.

 The index [] operator is used to access the elements of tuple.


Example:
a = (‘H’,’E’,’L’,’L’,’O’) #Create Tuple
a[0] a[1] a[2] a[3] a[4]
H E L L O

a[-5] a[-4] a[-3] a[-2] a[-1]

>>> a[4]
'O'
>>> a[-4]
'E'
Tuples are immutable
 Unlike Lists we cannot change the elements of tuples.

>>> 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
 The + operator - The concatenation + operator is used to join two tuples.
Example:
>>> a=('A','B')
>>> b=(1,2)
>>> a+b
('A', 'B', 1, 2)
>>> type(a+b)
<class 'tuple'>
 The * operator – It is used to replicate the elements of a tuple.
>>> t = (1,2,3)
>>> t *2
(1, 2, 3, 1, 2, 3)
Passing Variable Length Arguments to a Tuple
 You can pass variable number of parameters to a function.
 A argument that begins with * in function definition gathers arguments into a tuple.
Example:

def create_tup(*args):
print(args)

Run the above program from interactive mode of Python

>>> create_tup(1,2,3,4)
(1, 2, 3, 4)
>>> create_tup('a','b')
('a', 'b')
Sorting elements of Tuple
 Tuple does not support any sort method to sort the contents of Tuple.

 Following are the steps required to sort the elements of Tuple.


a. Create Tuple
b. Convert Tuple to List
c. Use sort method of list
d. Convert back from list to 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

 The zip() is one of the built in python functions.

 The zip() function take items in sequence from a number of collections to make a list of tuples.

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.
 
s.clear() Removes the entire element from the existing set.
 
S.remove(x) Removes item x from the set.
 
  A set S1 is a subset of S2, if every element in S1 is also
S1. issubset(S2) in S2. Therefore issubset() is used to check whether s1
  is subset of s2.
 
  Let S1 and S2 be two sets. If S1 is subset of S2 and the
S2.issuperset(S1) set S1 is not equal to S2 then the set S2 is called
 
superset of A.
Set Operations
 The union() method
The union of two sets A and B is the set of elements which are in A, in B, or in both A and B.

Example:
>>> A = {1,2,3,4}
>>> B = {1,2}
>>> A.union(B)
{1, 2, 3, 4}
Set Operations…..
 The intersection() method
Intersection is a set which contains the elements that appear in both sets.

Example:
>>> A = {1,2,3,4}
>>> B = {1,2}
>>> A.intersection(B)
{1, 2}

Note: A. intersection(B) is equivalent to A & B


Set Operations…..
 The difference() method
The difference between two sets A and B is a set that contains the elements in set A but not in set B.

Example:
>>> A = {1,2,3,4}
>>> B = {2,5,6,7,9}
>>> A.difference(B)
{1, 3, 2}

Note: A.difference B is equivalent to A - B


Set Operations…..
 The symmetric_difference() method
It contains the elements in either set but not in both sets.

Example:
>>> A = {1,2,3,4}
>>> B = {2,5,6,7,9}
>>> A.symmetric_difference(B)
{1,3,4,5,6,7,9}

Note: A. symmetric_difference B is equivalent to A^B


Introduction to Dictionaries
 In python a dictionary is a collection that stores the values along with the keys.
 The sequence of key and value pairs are separated by commas.
 These pairs are sometimes called entries or item.
 All entries are enclosed in curly braces { and }.

Example:
{'India': '+91', 'USA': '+1'}

Key Value Key Value


Creating Dictionaries
 The dictionary can be created by enclosing the items inside the pair of curly braces { }.

Example:
>>> D = { }
>>> type(D)
<class 'dict'>
>>> D={'Virat Kohli':52,'Sachin':100}
>>> D
{'Sachin': 100, 'Virat Kohli': 52}
>>> type(D)
<class 'dict'>
Adding new entries to a Existing Dict
 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?


keys() Returns the sequence of keys.
Values() Return sequence of Values.
items() Return the sequence of Tuples.
clear() Delete all entries
get(key) Return the value for the key.
pop(key) Removes the key and returns the value
if the key exist.
clear() Remove all the keys.
Traversing a Dictionary
 A for loop is used to traverse all keys and values of a dictionary.
 The variable of a for loop is bound to each key in unspecified order.
Example:

D={'Virat Kohli':52,'Sachin':100, 'Dhoni': 28}


for key in D:
print('Centuries scored by ',key,'=',D[key])

Output:

Centuries scored by Sachin = 100


Centuries scored by Virat Kohli = 52
Centuries scored by Dhoni = 28
Nested Dictionaries
 Dictionaries within Dictionaries is said to be nested dictionaries.

Example:
>>> Players={"Virat Kohli" : { "ODI": 7212 ,"Test":3245},
"Sachin Tendulkar" : {"ODI": 18426 ,"Test":15921}}
>>> Players
{'Sachin Tendulkar': {'Test': 15921, 'ODI': 18426}, 'Virat Kohli': {'Test': 3245, 'ODI': 7212}}
Conclusion
 Tuples are immutable
 Set is an unordered collection of elements without duplicates.
 Sets are mutable.
 A dictionary is a collection that stores the values along with the keys.

You might also like