Tuples in Python
Tuples are immutable sequences of Python i.e., you
can not change elements of a tuple in place.
Difference from
Lists
The main difference between the tuples and the lists is
1) that the tuples cannot be changed unlike lists i.e., they
are immutable .
2) Tuples use parentheses, whereas lists use square
brackets.
Creating And
Accessing Tuples
Method 1:
Place these comma-separated values between parentheses also.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
>>> print (tup1)
('physics', 'chemistry', 1997, 2000)
Method 2 : Creating a tuple is as simple as putting different
comma-separated values.
tup3 = "a", "b", "c", "d"
>>> print (tup3)
Output :
('a', 'b', 'c', 'd')
Empty Tuple:
T=tuple()
T=()
Single Element Tuple:-
T=(10)
________
Updating Tuples
Tuples are immutable, which means we cannot update or change the values of tuple
elements. It is possible to take portions of the existing tuples to create new tuples as
the following example demonstrates −
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')
Tuple1=(0,1,2,3)
Tuple2=(‘Geeks’, ‘For’, ‘Geeks’)
Tuple1+Tuple2
Delete Tuple Elements
Tup=(1,2,3,4)
del Tup[1]
________
del Tup
1. a=1; b=2; c=3; d=4; e=5
Tup=(a,b,c,d,e)
e1,e2,e3,e4,e5=Tup
print(e1,e2,e3,e4,e5)
2. a=1; b=2; c=3; d=4; e=5
Tup=(a,b,c,d,e)
e1,e2,e3,e4=Tup
_______________________
1. a=1; b=2; c=3; d=4; e=5
Tup=(a,b,c,d,e)
e1,e2,e3,e4,e5=Tup
print(e1,e2,e3,e4,e5)
2. a=1; b=2; c=3; d=4; e=5
Tup=(a,b,c,d,e)
e1,e2,e3,e4=Tup
ValueError: too many values
to unpack (expected 3)
a=1; b=2; c=3; d=4; e=5
Tup=(a,b,c,d,e)
e1,*e2,e3=Tup
print(e1) # __________
print(e2) # __________
print(e3) # __________
Practice
fruits= ["mango", "apple", "banana","guava"]
[Link]( )
print(fruits)
print(fruits[1:3])
[Link](reverse=True)
print(fruits)
print(fruits[1:3])
bright=('red','green','blue')
light= ('pink','grey')
bright = bright + light
print(bright)
a1=(11,22,33)
a = list(a1) # typecasting tuple to list
print(a)
a[1] = 909
print(a)
1. Write a program to accept a list of numbers and a threshold number.
The program should return a new list containing 1s and 0s. The ith entry
of the new list is 1 if the ith entry of the old list is greater than or equal to
threshold, and 0 otherwise. An example: if the inputs are[10, 2, 5, 8] and
if the threshold is 5, the
output should be [1, 0, 1, 1].
Dictionary:
A dictionary is an object that stores a collection of data. Each element in a
dictionary has two parts: a key and a value. Each key is separated from its
value by a colon (:) . The items are separated by commas, and the whole
is enclosed in curly braces. A key can be used to locate a specific value.
An empty dictionary is one without any items in it and is written with just
two curly braces, {}.
Keys are unique within a dictionary while values may not be. The values in
a dictionary can be objects of any type, but the keys must be immutable
objects. For example, keys can be strings, integers, floating-point values,
or tuples. Keys cannot be lists or any other type of immutable object.
Displaying the dictionary
>>> phonebook= {'Lata': 9845473653, 'Shaji':9447473653, 'Jayram':
9447473666, 'Santosh':7179764751}
>>> phonebook['Shaji']
9447473653
>>> phonebook['shaji']
Traceback (most recent call last):File "<pyshell#3>", line 1, in <module>
phonebook['shaji’] KeyError: 'shaji'
Updating Dictionary
>>> phonebook['Lata’] = 7792749469
>>> phonebook[‘Manish’]=7778898941
Create a Dictionary by Using zip( ) Function:
>>> a=(1,2,3,4)
>>> b=(‘hi’, ‘bye’, ‘HI’, ‘BYE’)
>>> D=dict(zip(a,b))
>>> D
{ 1:’hi’, 2:’bye’, 3:’HI’, 4:’BYE’ }
Create a Dictionary by Using zip( ) Function:
>>> a=(1,2,3,4)
>>> b=(‘hi’, ‘bye’, ‘HI’)
>>> D=dict(zip(a,b))
>>> D
________________
>>> a=[1,2,3]
>>> b=( 10,20,30,40)
>>> D=dict(zip(a,b))
>>> D
__________________
Delete Dictionary Elements
1. To remove individual dictionary element
>>> del phonebook['Shaji']
>>> phonebook
{'Lata': 7792749469, 'Jayram':9447473666, 'Santosh':7179764751}
2. To remove all entries in dict
>>> [Link]()
>>> phonebook
{}
3. To delete entire dictionary
>>>_____________________
Iterating over a Dictionary
>>> d = {"a":123, "b":34,
"c":304, "d":99}
>>> for key in d:
print(key)
a
b
c
d
Dictionary methods :
mymarks = {"eng" : 20 , "maths" : 15 , "comp sc" : 25 , "phy" : 3 , "chem" : 9}
1. [Link]() : Removes all elements of dictionary dict
2. [Link]() : Returns a shallow copy of dictionary dict
>>> marks = [Link]()
>>> print (marks)
{'eng': 20, 'maths': 15, 'comp sc': 25, 'phy': 3, 'chem': 9}
3. [Link](key) : Returns value of key
>>> [Link]("maths")
15
4. [Link]() : Returns a list of dict's (key, value) tuple pairs
>>> [Link]()
dict_items([('eng', 20), ('maths', 15), ('comp sc',25), ('phy', 3), ('chem', 9)])
5. [Link]() : Returns list of dictionary dict's keys
>>> [Link]()
dict_keys(['eng', 'maths', 'comp sc', 'phy', 'chem'])
Practice
>>> d1={1:2,2:3,3:4}
>>> f=[Link]()
>>> f
dict_keys([1, 2, 3])
>>> type(f)
_________
>>> f[0]
__________
>>> g=str(f)
__________
>>>g[1]
__________
Practice
>>> d1={1:2,2:3,3:4}
>>> f=[Link]()
>>> f
dict_keys([1, 2, 3])
>>> type(f)
<class 'dict_keys'>
>>> f[0]
TypeError: 'dict_keys' object is not subscriptable
>>> g=str(f)
>>>g[1]
'i'
Practice
>>> d1={1:2,2:3}
>>> d2=d1 >>> d3
>>> d2[3]=4 ___________
>>> d2 >>> id(d3)
___________ ___________
>>> d1 >>> id(d1[1])
___________ ___________
>>> id(d1) >>> id(d2[1])
___________ ___________
>>> id(d2) >>> id(d3[1])
___________ ___________
>>> d3=[Link]()
Practice
>>> d1={1:2,2:3}
>>> d2=d1 >>> d3
>>> d2[3]=4 {1: 2, 2: 3, 3: 4}
>>> d2 >>> id(d3)
{1: 2, 2: 3, 3: 4} 2155071831936
>>> d1 >>> id(d1[1])
{1: 2, 2: 3, 3: 4} 140721996948424
>>> id(d1) >>> id(d2[1])
2155071831616 140721996948424
>>> id(d2) >>> id(d3[1])
2155071831616 140721996948424
>>> d3=[Link]()
Dictionary methods :
6. [Link]() : Returns list of dictionary dict's values
>>> [Link]()
dict_values([20, 15, 25, 3, 9, 'A1', 'B2’])
7. [Link](dict2) : Adds dictionary dict2's key-values pairs to dict
>>> others = {"gs" :"A1" , "hpe" : "B2"}
>>> [Link](others)
>>> mymarks
{'eng': 20, 'maths': 15, 'comp sc': 25, 'phy': 3,
'chem': 9, 'gs': 'A1', 'hpe': 'B2’}
8. [Link](k) : Removes the key k with its value from the dictionary D and returns the
corresponding value as the return value, i.e. D[k]. If the key is not found a KeyError is raised
>>> capitals = {"Austria":"Vienna", "Germany":"Berlin", "Netherlands":"Amsterdam"}
>>> capital = [Link]("Austria")
>>> print(capital)
Vienna
>>> print(capitals)
{'Germany': 'Berlin', 'Netherlands': 'Amsterdam'}
Dictionary methods :
9. [Link]() : It is a method of dict, which doesn't take any parameter and removes and
returns an arbitrary (key,value) pair. If popitem() is applied on an empty dictionary, a KeyError
will be raised.
capitals = {"Springfield":"Illinois",
"Augusta":"Maine", "Boston": "Massachusetts",
"Lansing":"Michigan", "Albany":"New York",
"Olympia":"Washington", "Toronto":"Ontario"}
>>> (city, state) = [Link]()
>>> (city, state)
('Toronto', 'Ontario')
>>> (city, state) = [Link]()
>>> (city, state)
('Olympia', 'Washington')
Dictionary methods :
10. setdefault(key, default_value)
key - the key to be searched in the dictionary
default_value (optional) - key with a value default_value is inserted to the dictionary if the key
is not in the dictionary.
If not provided, the default_value will be None.
Example 1: How setdefault() works when key is in the dictionary?
person = {'name': 'Phill', 'age': 22}
age = [Link]('age')
print('person = ',person)
print('Age = ',age)
Output
__________________
Example 2: How setdefault() works when key is not in the
dictionary?
OUTPUT
____________
Dictionary methods :
11. fromkeys()
The fromkeys() method creates a dictionary from the given sequence of keys and values.
OUTPUT
____________
1) Write Program to count the frequency of elements in a list using a
dictionary.
2) Write a menu driven program to implement the following using dictionary :
Friends and Their Birthdays
----------------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program
Enter your choice :
Random Module
random() Returns a random float number between 0 and 1
randint() Returns a random number between the given range
randrange() Returns a random number between the given range
uniform() Returns a random float number between two given parameters
seed() Initialize the random number generator
getstate() Returns the current internal state of the random number generator
setstate() Restores the internal state of the random number generator
choice() Returns a random element from the given sequence
choices() Returns a list with a random selection from the given sequence
sample() Returns a given sample of a sequence
import random
# remember this state
state = [Link]()
# print 10 random numbers
print([Link](range(20), k = 10))
print(state)
# restore state
[Link](state)
# print same first 5 random numbers
# as above
print([Link](range(20), k = 5))
import random
mylist = ["geeks", "for", "python"]
print([Link](mylist, weights=[2,10,1], k = 5))
>>> import time
[Link] [Link]() Function
time.struct_time(tm_year=2024, tm_mon=12, tm_mday=7, tm_hour=5,
tm_min=25, tm_sec=4, tm_wday=5, tm_yday=342, tm_isdst=0)
2. [Link]()
1733549934.2810867
[Link]()
1733549938.9558039
3. [Link]()
'Sat Dec 7 [Link] 2024’
4. [Link](3)