List Tuple String Dictionary
List Tuple String Dictionary
random module
Word random in English means unpredictable, unspecified or without any fixed pattern. Example of event
in real life: tossing of coin, rolling of dice and picking a card from a deck of cards. In Python we have
module random, which generates pseudo random numbers (either int or float). We will consider four
functions from the random module:
1. randint()
randint(start,stop): generates a random integer between start and stop including
start and stop. Both start and stop are integer type and start<=stop. If either start or
stop are float then randint() function will trigger an error. If start<stop then randint()
function will trigger an error. Examples are given below:
from random import randint
for x in range(20):
num=randint(1,9) #generates single digit random integer
print(num, end=' ')
Running of the program produces following output:
6 5 9 3 1 3 2 4 8 6 1 4 9 4 9 2 3 9 7 2
randint(10,99) - will generate 2 digit random integer between 10 and 99
randint(-99,-10) - will generate 2 digit negative random integer between -99 and -10
randint(10,500) - will generate digit random integer between 10 and 500
randint(99,10) - will trigger an error since start > stop
randint(10.0, 99) - will trigger an error since start is float
2. randrange()
• randrange(stop): generates a random integer between 0 (zero) and stop including 0
but excluding stop(stop-1). stop is integer type. If stop is either float or negative integer
or zero (0) then, randrange() function will trigger an error. Examples are given below:
from random import randrange
for x in range(20):
num=randrange(6) #generates random integer between 0 and 5
print(num, end=' ')
Running of the program produces following output:
4 2 3 0 3 1 1 5 2 1 4 1 1 5 2 3 3 2 5 0
randrange(10.0) – will trigger an error since stop is float
randrange(0) – will trigger an error since stop is zero (0)
• randrange(start,stop): generates a random integer between start (start) and stop
(stop) including start but excluding stop(stop-1). Both start and stop are integer
type and start<=stop. If either start or stop are float then randrange() function will
trigger an error. If start<stop then randrange() function will trigger an error. Function
randint() internally calls function randrange(), that is, randint (11, 20) is internally
called as randrange(10, 21). Examples are given below:
from random import randrange
for x in range(20):
num=randrange(1, 10) #generates single digit random integer
print(num,end=' ')
Running of the program produces following output:
3 7 1 9 8 7 6 2 9 2 3 2 7 1 9 2 2 4 9 5
randrange(10,99) - will generate 2 digit random integer between 10 and 98
randrange(10,500) - will generate random integer between 10 and 499
randrange(-100,-10) - will generate 2 digit negative random integer between -99 and -10
randint(99,10) - will not generate any random integer since start > stop
randrange(99,10) - will trigger an error since start > stop
randint(10.0, 99) - will trigger an error since start is float
The lists list1 , list2 and list4 contains homogeneous values. The list list3 and list5
contains heterogeneous collection. The list list6 and list list7 is an empty list (the two lists do not
contain any value).
Every value stored in the list is called an element of the list.
0 1 2 3 4
Every element in the list is assigned an index starting from 0
list1 10 20 30 40 50 (zero). The first element in the list from the left is assigned
-5 -4 -3 -2 -1 an index 0, the second element in the list from the left is
assigned an index 1, the third element in the list from the
0 1 2 3 left is assigned an index 2 and last the last element in the list
list2 2.3 4.5 6.7 8.9 (from left) is assigned (number of elements - 1) as an index.
-4 -3 -2 -1 Python supports negative index. First element from left will
have index starting from length of list. Last element of a list
0 1 2 3 will have an index -1. Traversing a list from left to right,
list3 15 2.5 35 4.5 index is incremented by 1. Traversing a list from right to
-4 -3 -2 -1 left, index is decremented by 1.
>>> print(list6)
Displays [] since alist6 is an empty list (does not contain any element / value)
As mentioned earlier, print() function will display the entire list from left to right. But when working
with a list, we need to access the individual elements / values stored in the list. Each element of a list can
be accessed as:
listname[pos]
Data type for list pos must be an int. If a list has n elements then n indices are:
• 0, 1, 2, …, n-3, n-2, n-1 (non-negative index starting from 0)
• -n, -(n-1), -(n-2), …, -3, -2, -1 (negative index)
If index is out of range (access an element with an invalid index), will trigger a run-time error.
0 1 2 3 4
list1 10 20 30 40 50
-5 -4 -3 -2 -1
print()
As discussed earlier, function print() displays the entire list on the screen from left to right.
>>> student=[24, 'TARUN', 'COMP SC', 56, 25]
>>> print(student)
Displays [24, 'TARUN', 'COMP SC', 59, 28]
len()
Function len() returns number of values (elements) present in a list. Function len() works with list
of any type.
>>> a=[55,45,25,65,15]
>>> b=[2.5,6.7,9.3,5.7,1.2]
>>> c=['DIPTI','AVEEK','SANDIP','NEETA','BHUVAN']
>>> d=[11.5,12,13.5,15,14.5,10]
>>> e=[1001,'PRATAP JAIN','MANAGER','FINANCE', 250000.0]
>>> print(len(a),len(b),len(c),len(d),len(e))
Displays 5 5 6 6 5
Function len() will return 0, if the list is empty.
max(), min()
Function max() returns the maximum value (highest / largest value) stored in the list. Function min()
returns the minimum value (lowest / smallest value) stored in the list. Functions max() and min() can
be used with list containing either homogeneous data type (either only int or only float or only str)
or list containing only numbers (int type values and float type values). Using functions max() and
min() with list containing int (float) type values and str type values will trigger run-time error.
>>> a=[55,45,25,65,15]
>>> b=[2.5,6.7,9.3,5.7,1.2]
>>> c=['DIPTI','AVEEK','SANDIP','NEETA','BHUVAN']
>>> d=[11.5,12,13.5,15,14.5,10]
>>> e=[1001,'PRATAP JAIN','MANAGER','FINANCE', 250000.0]
>>> print(max(a),max(b),max(c),max(d))
Displays 65 9.3 SANDIP 30
>>> print(min(a),min(b),min(c),min(d))
Displays 15 1.2 AVEEK 1.5
>>> print(max(e))
Displays run-time error since type str and type int(float) type and cannot be compared using either
> or < operator.
>>> print(min(e))
Displays run-time error since type str and type int(float) type and cannot be compared using either
> or < operator.
sorted()
Function sorted() returns a list sorted in ascending order by default but it does not sort the list.
Function sorted()can be used with list containing either homogeneous data type (either only int or
only float or only str) or list containing only numbers (int type values and float type values). By
default function sorted() will return a list sorted in ascending order. By using reverse=True, will
return a list sorted in descending order. If a list contains int (float) type values and str type values,
using functions sorted() will trigger run-time error.
>>> a=[55,45,25,65,15]
>>> b=[2.5,6.7,9.3,5.7,1.2]
>>> c=['DIPTI','AVEEK','SANDIP','NEETA','BHUVAN']
>>> d=[11.5,12,13.5,15,14.5,10]
>>> e=[1001,'PRATAP JAIN','MANAGER','FINANCE', 250000.0]
>>> print(sorted(a))
Displays [15, 25, 45, 55, 65]
>>> print(a)
Displays [55,45,25,65,15], the unsorted list (does not sort the list)
>>> print(sorted(b))
Displays [1.2, 2.5, 5.7, 6.7, 9.3]
>>> print(sorted(c))
Displays ['AVEEK', 'BHUVAN', 'DIPTI', 'NEETA', 'SANDIP']
>>> print(sorted(d))
Displays [10, 11.5, 12, 13.5, 14.5, 15]
>>> print(sorted(a, reverse=True))
Displays [65, 55, 45, 25, 15]
>>> print(sorted(b, reverse=True))
Displays [9.3, 6.7, 5.7, 2.5, 1.2]
>>> print(sorted(c, reverse=True))
Displays ['SANDIP', 'NEETA', 'DIPTI', 'BHUVAN', 'AVEEK']
>>> print(sorted(e))
Triggers run-time error since list containing str type and int(float) type and cannot be compared
using either > or < operator.
How to store values in a list by inputting values from the keyboard during the run-time:
• List containing homogeneous values
#Program01 - list of int Variable alist is an empty list. Statement
alist=[] #alist=list() alist+=[num]
n=int(input('No. of elements? ')) OR, alist.append(num)
for k in range(n): will append value stored in the variable num to
num=int(input('Integer? ')) the list. Since the variable num is an integer type,
alist+=[num] all the elements in the list will be of the type
#alist.append(num) integer.
print(alist)
• List containing homogeneous values
#Program02 - list of float Variable alist is an empty list. Statement
alist=[] #alist=list() alist+=[num]
n=int(input('No. of elements? ')) OR, alist.append(num)
for k in range(n): will append value stored in the variable num to
num=float(input('Value? ')) the list. Since the variable num is a float type, all
alist+=[num] the elements in the list will be of the type float.
#alist.append(num)
print(alist)
Variable alist is an empty list. Statement
• List containing homogeneous values
#Program03 - list of str alist+=[astr]
alist=[] #alist=list() OR, alist.append(astr)
n=int(input('No. of elements? ')) will append value stored in the variable astr to
for k in range(n): the list. Since the variable astr is a str type, all
astr=input('String? ') the elements in the list will be of the type str.
• Linear search
Sequentially a value is searched in a list starting form the first element (starting from left or stating
from index 0). Either the value is in the list or the value is not in the list. If value is located in the list,
there is no need to search any more.
from random import randint
n=int(input('No. of elements? '))
alist=[randint(10,99) for k in range(n)]
print(alist)
item=int(input('Item to search? '))
FAIPS, DPS Kuwait Page 17 of 18 © Bikram Ally
Python Notes Class XI List
found=0
Search item (item) is compared
for k in range(n):
if item==alist[k]: with every element in the list. If the
found=1 search item is found in the list, flag
break variable found is updated to 1 and
if found: the while loop terminates. If the
print(item, 'found in the list') search item is not in the list, the while
else: loop terminates when k==n (end of
print(item, 'not found in the list') the list). Value stored in the flag
''' variable found is tested after the
found=k=0 while loop.
while k<n:
if item==alist[k]:
found=1
break
k+=1
OR,
found=k=0
while k<n and found==0:
if item==alist[k]: found=1
k+=1
if found:
print(item, 'found in the list')
else:
print(item, 'not found in the list')
OR,
for k in range(n):
if item==alist[k]:
print(item, 'found in the list')
break
else:
print(item, 'not found in the list')
OR,
k=0
while k<n:
if item==alist[k]:
print(item, 'found in the list')
break
k+=1
else:
print(item, 'not found in the list')
'''
The tuple tup1 contains 5 int type values (homogeneous collection). The tuple tup2 contains 4
float type values (homogeneous collection). The tuple tup3 contains 2 int type values and 2 float
type values (heterogeneous collection). The tuple tup3 contains 5 str type values (homogeneous
collection). The tuple tup4 contains 1040 - int type value, 'SANDEE GARG', 'MANAGER' - str
type value, 150000.0 - float type value (heterogeneous collection). The tuples tup5 is empty tuple
(the tuple does not contain any value). Values in a tuple are enclosed within (). The concept of index in
tuple is exactly same as concept of index in list.
>>> print(tup1)
Displays tuple from left to right including () as (100, 200, 300, 400, 500)
Function print() will print/display the entire tuple on the screen from left to right. But when processing
a tuple, we need to access the elements of the tuple.
How to access an element in a tuple? To access an element in a tuple we need to do the following:
tuplename[index]
Data type for index must be an int. If a tuple has n elements then indices are:
• 0, 1, 2, …, n-3, n-2, n-1
• -n, -(n-1), -(n-2), …, -3, -2, -1
If index is out of range (access an element with an invalid index), will trigger a run-time error.
Why to access an element of a tuple? One needs to access an element from a tuple for the following:
• To display the value stored in the element
• To use the value stored in the element for some calculation or for some processing
len()
Function len() returns number of elemnets present in a tuple.
max(), min()
Function max() returns the highest value stored a tuple. Function min() returns lowest value stored in
a tuple. The tuple must contain only numbers or only strings. If the tuple contains numbers and string.
Functions max() and min() will trigger a run-time error.
sum()
Function sum() returns the sum of the values stored in a tuple, if tuple contains only numbers. If a tuple
contains numbers and string or the tuple contains strings then sum() will trigger a run-time error.
sorted()
Function sorted() will return values present in a the tuple, as a sorted list in ascending order but it does
not sort the tuple. Using reverse=True will return a sorted list in descending order. The function
sorted() will only return a sorted list when a tuple contains either numbers or strings. But if a tuple
contains numbers and strings, then sorted() will trigger a run-time error.
>>> tup=(40,20,50,10,30)
>>> sorted(tup)
Displays [10,20,30,40,50]
>>> print(tup)
Displays the unsorted tuple as (40,20,50,10,30)
>>> tup=(40,20,50,10,30)
>>> sorted(tup, reverse=True)
Displays the tuple sorted in descending order as [50,40,30,20,10]
>>> print(tup)
Displays the unsorted tuple as (40,20,50,10,30)
Searching in a tuple
When searching for value is a tuple, we are only reading a value that is being stored in an element of a
tuple. Linear search can be applied in any tuple (either sorted or unsorted). Binary search can only applied
in a sorted tuple.
• Linear search
from random import randint
n=int(input('No. of elements? '))
tup=()
for k in range(n): tup+=(randint(10,99),)
print(tup)
item=int(input('Item to search? '))
found=False
for k in range(n):
if item==tup[k]:
found=True
break
if found:
print(item, 'found in the list')
else:
print(item, 'not found in the list')
• Linear search
from random import randint
n=int(input('No. of elements? '))
tup=()
for k in range(n): tup+=(randint(10,99),)
FAIPS, DPS Kuwait Page 7 of 9 © Bikram Ally
Python Notes Class XI Tuple
print(tup)
item=int(input('Item to search? '))
for k in range(n):
if item==tup[k]:
print(item, 'not found in the list')
break
else:
print(item, 'found in the list')
• Linear search
from random import randint
n=int(input('No. of elements? '))
tup=()
for k in range(n): tup+=(randint(10,99),)
print(tup)
item=int(input('Item to search? '))
for ele in tup:
if item==ele:
print(item, 'not found in the list')
break
else:
print(ele, 'found in the list')
• Linear search
from random import randint
n=int(input('No. of elements? '))
tup=()
for k in range(n): tup+=(randint(10,99),)
print(tup)
item=int(input('Item to search? '))
found=False
for ele in tup:
if item==ele:
found=True
break
if found:
print(item, 'found in the list')
else:
print(item, 'not found in the list')
• Processing a tuple
#Program01 – sum of elements
from random import uniform
n=int(input('No. of elements? '))
tup=tuple([round(uniform(10,99),1) for k in range(n)])
s=0
for k in range(n):
s+=tup[k]
print(tup[k], end=' ')
print('\nSum=',s)
• Processing a tuple
#Program02 – to find AM, GM, HM of elements
from random import uniform
n=int(input('No. of elements? '))
tup=tuple([round(uniform(10,99),1) for k in range(n)])
su, sr, pr=0, 0,1
for k in range(n):
FAIPS, DPS Kuwait Page 8 of 9 © Bikram Ally
Python Notes Class XI Tuple
su+=tup[k]
pr*=tup[k]
sr+=1/tup[k]
print(tup[k], end=' ')
am, gm, hm=su/n, pr**(1/n), n/sr
print('\nAM=',am)
print('GM=',gm)
print('HM=',hm)
• Processing a tuple
#Program03 – to count number of odd elements and even elements
from random import uniform
n=int(input('No. of elements? '))
tup=tuple([round(uniform(10,99),1) for k in range(n)])
co=ce=0
for k in range(n):
if tup[k]%2==1:
co+=1
else:
ce+=1
print(tup[k], end=' ')
print('\nNo. Of Odd Elements=',co)
print('No. Of Even Elements=',ce)
• Processing a tuple
#Program04 – sum and avg of odd elements and even elements
from random import uniform
n=int(input('No. of elements? '))
tup=tuple([round(uniform(10,99),1) for k in range(n)])
co=ce=0
so=se=0
for k in range(n):
if tup[k]%2==1:
so+=tup[k]
co+=1
else:
se+=tup[k]
ce+=1
print(tup[k], end=' ')
print()
avo=so/co
ave=se/ce
print('Number of Odd Elements=',co,'\nSum=',so,'\nAvgerage=',avo)
print('Number of Even Elements=',ce,'\nSum=',se,'\nAvgerage=',ave)
String str1 contains ASCII characters and string str2 and str3 contains Unicode characters. However, will
work with strings that contains ASCII characters. A string is a sequence hence it supports index (both non-
negative and negative index). String is a homogeneous collection since it contains only characters (string with
single element). A string literal is enclosed with single quote (') or double quote (") or triple single quote (''') or
triple double quote (""").
>>> print(str1)
Displays the string str1 as MANGO. Kindly note, when a string displayed, the delimiters are not displayed.
How to access a character in a string? To access a character in a string we need to do the following:
strname[index]
Data type for index must be an int. If a string has n characters then indices are:
• 0, 1, 2, …, n-3, n-2, n-1 Non-negative index
• -n, -(n-1), -(n-2), …, -3, -2, -1 Negative index
If index is out of range (access a character with an invalid index), will trigger a run-time error.
>>> str1='MNAGO'
>>> for k in range(5): print(str1[k],end=' ')
Displays the string left to right: M A N G O
>>> for k in range(1,5): print(str1[-k],end=' ')
Displays the string right to left: O G N A M
>>> for ch in str1: print(ch,end=' ')
Displays the string left to right: M A N G O
FAIPS, DPS Kuwait Page 1 of 10 © Bikram Ally
Python Notes Class XI String
>>> print(str1[6])
>>> print(str1[-6])
Displays run-time error: string index out of range since a string has only 5 characters.
len()
Function len() returns number of characters present in a string.
>>> str1,str2='FAIPS-DPS',""
>>> print(len(str1), len(str2))
Display 9 0
max(), min()
Function max() returns the character with highest ASCII code / Unicode from a string. Function min() returns
the character with lowest ASCII Code (Unicode) from a string.
>>> str1='FAIPS'
>>> print(max(str1), min(str1))
Display S A
sorted()
Function sorted() returns a list containing characters present in the string sorted in ascending order but does
not sort the characters present in the string. Using reverse=True returns a list sorted in descending order.
>>> str1='FAIPS'
>>> sorted(str1)
Displays ['A', 'I', 'F', 'P', 'S']
>>> sorted(str1, reverse=True)
Displays ['S', 'P', 'I', 'F', 'A']
>>> print(str1)
Displays FAIPS
sorted() sort()
• It is a built-in function • It is a list method
• Returns a list • Returns None
• Does not sort a list / tuple / string / dictionary • Sorts a list physically, by default elements are
physically sorted in ascending order
• Accepts list / tuple / string / dictionary (iterable) as • Does not accept tuple / string / dictionary (any
a parameter iterable) as a parameter
List Tuple
• A list is delimited by [] • A tuple is delimited by ()
• For a list, delimiter [] is mandatory • For a tuple, delimiter () is optional
• A list type data is mutable • A tuple type data is immutable
• An element of a list can be updated using = • An element of a tuple cannot be updated using =
• An element of a list can be deleted with del • An element of a tuple cannot be deleted with del
• A list pass by reference to a function • A tuple is pass by value to a function
Mutable Immutable
• Can be updated • Cannot be updated
• = operator creates an alias • = operator creates a copy
• Since it can be updated, by updating a mutable type, • Since it cannot be updated, updating a mutable type
no new object is created will create a new object
• Since it can be updated, no new id is allocated • Since it cannot be updated, new id is allocated
• Passed as a reference parameter to a function • Passed as a value parameter to a function
Data type Features
FAIPS, DPS Kuwait Page 6 of 10 © Bikram Ally
Python Notes Class XI String
List Mutable type, collection, sequence, iterable type, built-in type
Tuple Immutable type, collection, sequence, iterable type, built-in type
String Immutable type, sequence, iterable type, fundamental type
Dictionary Mutable type, collection, mapping, iterable type, built-in type
Dictionary d1 is created with 3 key:value pairs. Key for every pair is an int type. Every value in the
dictionary d1 is a constant. Dictionary d2 is created with 3 key:value pairs. Key for every pair is a float
type. Every value in the dictionary d2 is a constant. Dictionary d3 is created with 3 key:value pairs.
Key for every pair is a str type. Every value in the dictionary d3 is a constant. Dictionary d4 is created
with 4 key:value pairs. Key for every pair is a str type. Values in the first 3 pairs are variable and value
for the last pair is an expression. Dictionary d5 is created where keys are string (str) type variable and
values are also variables. Dictionary d6 is created as an empty dictionary (without any key:value pairs).
>>> print(d1)
Displays {1: 1011, 2:'ABIJEET', 3: 78000.0}
>>> print(d2)
Displays {1.5: 1012, 2.5: 'SUNIL', 3.5: 75000.0}
>>> print(d3)
Displays {'eno': 1013, 'name': 'KARAN', 'bsal': 77000.0}
>>> print(d4)
Displays {'eno': 1014, 'name': 'DEEPAK', 'bsal': 76000.0, 'hra': 15200.0}
>>> print(d5)
Displays {'code': 1027, 'name': 'RADHIKA SINHA', 'bsal': 156000.0}
>>> print(d6)
Displays {}
Keys in a dictionary are supposed to be distinct. But what happens when a key is repeated?
>>> stu={'rn':10, 'na':'TARUN', 'th':50, 'pr':25, 'th':55}
>>> print(stu)
Displays {'rn':10, 'na':'TARUN', 'th':55, 'pr':25}
In the dictionary stu, key 'th' is repeated twice. If a key is repeated, key is assigned the last value for
the key from right and ignore the previous value(s) for key. Key:value 'th':55 replaces 'th':50.
FAIPS, DPS Kuwait Page 1 of 9 © Bikram Ally
Python Notes Class XI Dictionary
Function print(dictname) will display the entire dictionary. To display the keys present in a
dictionary one can use keys() method of a dictionary. Method keys() will return an iterable object
containing keys of the dictionary as a list. To display the values present in a dictionary one can use
values() method of dictionary. Method values() will return an iterable object containing values
present in a dictionary as a list. Elements present in iterable objects returned by keys() and values()
methods are not subscriptable, that is, elements cannot be accessed using an index.
>>> print(d1.keys())
Displays dict_keys([1, 2, 3])
>>> print(d2.keys())
Displays dict_keys([1.5, 2.5, 3.5])
>>> print(d3.keys())
Displays dict_keys(['eno', 'name', 'bsal'])
>> print(d4.keys())
Displays dict_keys(['eno', 'name', 'bsal', 'hra'])
>> print(d5.keys())
Displays dict_keys(['code', 'name', 'bsal'])
>>> print(d6.keys())
Displays dict_keys([])
>>> print(d1.values())
Displays dict_values([1011, 78000.0])
>>> print(d2.values())
Displays dict_values([1012, 'SUNIL', 75000.0])
>>> print(d3.values())
Displays dict_values([1013, 'KARAN', 77000.0])
>>> print(d4.values())
Displays dict_values([1014, 'DEEPAK', 76000.0, 15200.0])
>>> print(d5.values())
Displays dict_values(1027, 'RADHIKA SINHA', 156000.0])
>>> print(d6.values())
Displays dict_values([])