0% found this document useful (0 votes)
9 views46 pages

List Tuple String Dictionary

The document provides an overview of the Python random module, detailing functions like randint(), randrange(), random(), and uniform() for generating random numbers. It also explains the concept of lists in Python, including their creation, indexing, and accessing elements. The document includes examples and error handling for various scenarios related to these functions and lists.

Uploaded by

vishweshmalathi
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)
9 views46 pages

List Tuple String Dictionary

The document provides an overview of the Python random module, detailing functions like randint(), randrange(), random(), and uniform() for generating random numbers. It also explains the concept of lists in Python, including their creation, indexing, and accessing elements. The document includes examples and error handling for various scenarios related to these functions and lists.

Uploaded by

vishweshmalathi
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
You are on page 1/ 46

Python Notes Class XI List

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

FAIPS, DPS Kuwait Page 1 of 18 © Bikram Ally


Python Notes Class XI List
• randrange(start, stop, step): generates a random integer between start (start)
and stop (stop) including start but excluding stop (stop-1)with step as the common
difference. start, stop and step are integer type. A random integer is generated out of
start, start+step, start+2*step, start+3*step, … stop-1. If either start or
stop or step are float then randrange() function will trigger an error. If start<stop
and step is negative then randrange() function will trigger an error. If start>stop and
step is positive then randrange() function will trigger an error.
Examples are given below:
from random import randrange
for x in range(20):
num=randrange(10, 51, 5) #generates either 10/15/20/25/…/45/50
print(num, end=' ')
Running of the program produces following output:
15 30 25 15 15 25 35 10 50 30 15 15 40 15 45 30 25 10 50 45
randrange(10, 91, 10) - will generate 2 digit random integer which is a multiple of 10
randrange(10, 51, 2) - will generate 2 digit even random integer between 10 and 50
randrange(-30,-21,-2) - will generate random even negative integer between -30 and -20
randrange(90, 9, 3) - will trigger an error since start > stop and step>0
randrange(9, 90, -3) – will trigger an error since start < stop and step<0
randint(10, 101.0, 5) - will trigger an error since stop is float
3. random()
random() generates a random floating point number between 0 and 1, excluding 0 (zero) and
including 1. An example is given below:
from random import random
for x in range(10):
num=random() #generates a random value between 0 & 1
print(round(num, 4))
Running of the program produces following output:
0.6672 0.4854 0.6873 0.7550 0.0088 0.2033 0.2831 0.7641 0.7279 0.7927
4. uniform()
uniform(start, stop): generates a float type random value between start and stop
including start and stop. Both start and stop are numbers (either integer or float). If start
< stop then a random floating value is generated between start and stop. If start > stop then
a random floating value is generated between stop and start. This is unlike randint() and
randrange() functions, when start is greater than stop, an error is triggered. Examples are
given below:
from random import uniform
for x in range(8):
num=uniform(1, 9) #generates a random value between 1 & 9
print(round(num, 4), end=' ')
Running of the program produces following output:
1.7245 6.2180 6.2501 4.4136 8.8899 1.5373 6.7080 6.8809
from random import uniform
for x in range(8):
num=uniform(9, 1) #generates a random value between 9 & 1
print(round(num, 4), end=' ')
Running of the program produces following output:
8.0354 2.6453 4.1432 2.8452 3.9596 2.9638 3.1555 3.9742
uniform() function with single parameter or without any parameter will trigger an error.

FAIPS, DPS Kuwait Page 2 of 18 © Bikram Ally


Python Notes Class XI List
List
In Python a list is special type of variable used to represent many values under one variable name in the
RAM (Random Access Memory - main storage). A variable of fundamental data type like int or float or
str or bool or complex will store only one value under one variable name. A Python list type variable will
store many values under one variable name. A list in Python is either a homogeneous collection or a
heterogeneous collection. A list may be created in the following way:

listname=[value1, value2, value3, …]

>>> list1=[10, 20, 30, 40, 50]


>>> list2=[2.3, 4.5, 6.7, 8.9]
>>> list3=[15, 2.5, 35, 4.5]
>>> list4=['Sun', 'Mon', 'Tue', 'Wed', 'Thu']
>>> list5=[10, 'DILIP', 89.0, 'B1']
>>> list6=[] #creates an empty list, without any value
>>> list7=list() #creates an empty list, without any value

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.

0 1 2 3 4 A list in Python can contain any


list4 'Sun' 'Mon' 'Tue' 'Wed' 'Thu' type of data (int / float / str / …)
-5 -4 -3 -2 -1 but an index of a list is always an
int type (either a constant or a
0 1 2 3 variable or an expression). Index
list5 10 'DILIP' 89.0 'B1' always starts from left. Next index
-4 -3 -2 -1 is one more than the previous
index. If index starts from right,
>>> print(list1) previous index will be one less
Displays [10, 20, 30, 40, 50] than the current index. Displaying
a list with print() function, by
>>> print(list2) default will display the list from
Displays [2.3, 4.5, 6.7, 8.9] left to right including the delimiter
[] and values will be separated by
>>> print(list3) comma. String values present in
Displays [15, 2.5, 35, 4.5] the list will be displayed enclosed
with single quote (').
>>> print(list4)
Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu']

FAIPS, DPS Kuwait Page 3 of 18 © Bikram Ally


Python Notes Class XI List
>>> print(list5)
Displays [10, 'DILIP MEHTA', 89.0, 'B1']

>>> 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

Statement like, print(list1[5]) or print(list1[-7]) will trigger run-time error.

One needs to access an element a list for the following:


• To update the value stored in the element
• To display the value stored in the element
• To use the value stored in the element for some calculation / processing

>>> alist=[9329, 35.8, 'RIVER', 4783, 58.2, 'OCCEAN']


>>> for k in range(6): print(mylist[k], end=' ')
Displays the list from left to right as: 9329 35.8 RIVER 4783 58.2 OCCEAN
Control variable k of the for-loop generates the index for every element present in the list alist.
Instead one can also use while loop also:
>>> alist=[9329,35.8,'RIVER',4783,58.2,'OCCEAN']
>>> k=0
>>> while k<=5: #while k<6:
print(mylist[k], end=' ')
k+=1

>>> for k in range(1,7): print(alist[-k], end=' ')


Displays the list right to left: OCCEAN 58.2 4783 RIVER 35.8 9329
Using while-loop:
>>> k=1
>>> while k<=6: #while k<7:
print(mylist[-k], end=' ')
k+=1
In for loop, after the key word in one can use either a range() or an iterable object. Value of the type
string. list, tuple and dictionary are considered as an iterable object. Function range() generates
sequence of values (iterable object). One can use range() function with for loop to access all the
elements in a list. We can also use for loop with the list name (iterable object) to access all the elements
stored in a list.

FAIPS, DPS Kuwait Page 4 of 18 © Bikram Ally


Python Notes Class XI List
>>> for ele in alist: print(ele, end=' ')
Displays the list left to right: 9329 35.8 RIVER 4783 58.2 OCCEAN
In this case, control variable ele represents every element / value present in the list alist. Using a list
name as an iterable object is only possible using for loop. Using while-loop one can only use index
method to access the elements present in a list.

Using operators and keyword del with a list


Creates a new list
>>> marks=[] #marks=list() creates an empty list
>>> print(marks)
= Displays []
>>> marks=[24, 'TARUN', 'COMP SC', 56, 25]
>>> print(marks)
Displays [24, 'TARUN', 'COMP SC', 59, 28]
Assigns a value to an element of a list (updates value stored in an element)
>>> marks=[24, 'TARUN', 'COMP SC', 56, 25]
>>> marks[2]=59
= >>> marks[3]=28
>>> print(marks)
Displays [24, 'TARUN', 'COMP SC', 59, 28]
Creates an alias since list is a mutable type
>>> stu1=[12, 'RAHUL', 64]
>>> stu2=stu1
Now updating stu1, will update stu2 and vice versa. This is because list is a mutable type.
= >>> stu1+=[28] #updates stu2
>>> stu2+=[92] #updates stu1
>>> print(stu1, stu2)
Displays [12, 'RAHUL', 64, 28, 92] [12, 'RAHUL', 64, 28, 92]
Two lists contain identical (same) values (elements).
Joins to two or more lists (list concatenation)
>>> list1=[24, 'TARUN', 56]
>>> list2=[25, 81, 'B2']
>>> list3=list1+list2
>>> print(list3)
+
Displays [24, 'TARUN', 56, 25, 81, 'B2']
Only two (or more) lists can be concatenated
>>> alist=[10, 'AB', 7.2]
>>> alist=alist+(20, 'CD')
Above statement will trigger an error.
Updates an existing list by appending values from another iterable object
>>> stu=[24, 'TARUN']
>>> stu+=[25, 81]
>>> print(stu)
Displays [24, 'TARUN', 56, 25, 81]
>>> stu+=('B1', 'PASS')
>>> print(stu)
+= Displays [24, 'TARUN', 56, 25, 81, 'B1', 'PASS']
>>> alist=[3]
>>> alist+={'X':5, 4:2.5}
>>> print(alist)
Displays [3, 'X', 4] keys present in the dictionary are appended to the list
>>> alist+='MN'
Displays [3, 'X', '4', 'M', 'N'] characters in the string are appended to the list
FAIPS, DPS Kuwait Page 5 of 18 © Bikram Ally
Python Notes Class XI List
Replicate a list
>>> list1=[24, 'TARUN', 56]
>>> list2=3*list1
New list list2 is created by triplicating values stored in list list1.
>>> print(list2)
Displays [24, 'TARUN', 56, 24, 'TARUN', 56, 24, 'TARUN', 56]
>>> list2=-3*list1
New list list2 is created which is empty.
* >>> print(list2)
Displays []
>>> list2=0*list1
New list list2 is created which is empty.
>>> print(list2)
Displays []
>>> list2=2.5*list1
Triggers are error.
Updates an existing list by replicating values stored in the list
>>> stu=[24, 'TARUN', 56]
>>> stu*=2
The list stu is updated duplicating values stored in the list stu.
>>> print(stu)
Displays [24, 'TARUN', 56, 24, 'TARUN', 56]
>>> stu*=-2
*=
All the elements from list stu are deleted, the list becomes empty.
>>> stu=[24, 'TARUN', 56]
>>> stu*=0
All the elements from list stu are deleted, the list becomes empty.
>>> stu=[24, 'TARUN', 56]
>>> stu*=5.2
Triggers an error.
Checks whether an element is present in a list
>>> alist=[10, 20, 30, 40, 50]
>>> print(30 in alist, 60 in alist)
Displays True False
in >>> stu=[24, 'TARUN', 56]
>>> x='TARUN' in stu
>>> y='RANJIT' in stu
>>> print(x, y)
Displays True False
Deletes an element or elements from a list
>>> marks=[24, 'TARUN', 'COMP SC', 56, 25]
>>> del marks[2]
>>> print(marks)
Displays [24, 'TARUN', 56, 25]
Deletes the element whose index is 2
del >>> alist=[10,20,30,40,50]
>>> del alist[2], alist[2]
>>> print(alist)
Displays [10, 20, 50] since element whose is index 2 is deleted, so the list is left with 4
elements and next element from whose index 2 is deleted.
>>> del alist[5]
Displays run-time error because index 5 is out of range.

FAIPS, DPS Kuwait Page 6 of 18 © Bikram Ally


Python Notes Class XI List
Deletes a list
>>> marks=[24, 'TARUN', 'COMP SC', 56, 25]
del >>> del marks
>>> print(marks)
Displays run-time error because the list has been deleted from the memory.
Checks whether two lists are equal
>>> alist=[10, 20, 30]
>>> blist=[10, 20, 30]
>>> clist=[20, 10, 30]
== >>> print(alist==blist)
Displays True since corresponding elements of alist and blist are equal
>>> print(alist==clist)
Displays False since corresponding elements of alist and blist are not equal
Two lists are compared by checking the values present in the corresponding elements.
Checks whether two lists are not equal
>>> alist=[10, 20, 30]
>>> blist=[10, 20, 30]
>>> clist=[20, 10, 30]
!=
>>> print(alist!=blist)
Displays False since corresponding elements of alist and blist are equal
>>> print(alist!=clist)
Displays True since corresponding elements of alist and blist are not equal
Checks whether one list is greater than or equal to second list
>>> alist=[10, 20, 30]
>>> blist=[10, 20, 30]
>>> clist=[20, 10, 30]
>>> print(alist>blist)
Displays False since corresponding elements of alist and blist are equal
>>> print(alist>=blist)
>,>= Displays True since corresponding elements of alist and blist are equal
>>> print(alist>clist)
Displays False since 10 of alist is less than 20 of clist
>>> print(alist>=clist)
Displays False since 10 of alist is less than 20 of clist
If the two elements cannot be compared using > or <, then an error will be triggered.
>>> a, b=[10, 'AB'], [10, 20]
>>> print(a>b)
Triggers an error.
Checks whether one list is less than or equal to second list
>>> alist=[10, 20, 30]
>>> blist= [10, 20, 30]
>>> clist=[20, 10, 30]
>>> print(alist<blist)
Displays False since corresponding elements of alist and blist are equal
<,<=
>>> print(alist<=blist)
Displays True since corresponding elements of alist and blist are equal
>>> print(alist<clist)
Displays True since 10 of alist is less than 20 of clist
>>> print(alist<=clist)
Displays False since 10 of alist is less than 20 of clist

FAIPS, DPS Kuwait Page 7 of 18 © Bikram Ally


Python Notes Class XI List
Built-in functions for list data type
eval()
Built-in function eval() can be used to create a list during the run-time. An example is given below:
>>> stu=eval(input('Input Roll, Name, Marks? '))
>>> Input Roll, Name, Marks? [23, 'Rupak', 79.5]
Please remember, when inputting the values, start with [, inputted values are to be separated by comma
(,), string type data to be enclosed within quotes ('/") and end with ].
>>> print(stu)
Displays [23, 'Rupak', 79.5]
>>> stu=eval(input('Input Roll, Name, Marks? '))
>>> Input Roll, Name, Marks? [23, Rupak, 79.5]
Triggers a run-time error since RUPAK is inputted without quotes.

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.

FAIPS, DPS Kuwait Page 8 of 18 © Bikram Ally


Python Notes Class XI List
sum()
Function sum() returns the sum of the elements stored in the list, provided list contains only numbers
(all int type or all float type or only numbers). If a list contains str type value or list contains numbers
and strings, function sum() triggers a 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(sum(a))
Displays 205 (55+5+25+65+15)
>>> print(sum(b))
Displays 25.4 (2.5+6.7+9.3+5.7+1.2)
>>> print(sum(d))
Displays 76.5 (11.5+12+13.5+15+14.5+10)
>>> print(sum(c))
Displays run-time error since string type cannot be added to obtain a sum.
>>> print(sum(e))
Displays run-time error since integer type and string type cannot be added.

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.

FAIPS, DPS Kuwait Page 9 of 18 © Bikram Ally


Python Notes Class XI List
Functions from list class (methods of list class)
Appends an element in a list
>>> alist=[10,20,30,40]
>>> alist.append(50)
Appends 50 to the list (50 is added at the end, after 40).
>>> print(alist)
Displays [10, 20, 30, 40, 50]
append()
>>> alist.append([60,70])
Appends [60, 70] to the list.
>>> print(alist)
Displays [10, 20, 30, 40, 50, [60,70]]
>>> alist.append(80,90)
Triggers run-time error because append() needs one argument but two are given.
Values (elements(present) in am iterable is appended to a list
>>> alist=[10,20,30,40]
extend()
>>> alist.extend(iterable) is exactly same as alist+=ierable
Please refer to += operator discussed earlier.
Creates a new list which the duplicate of an existing list which is not an alias
>>> list1=[10,20,30,40]
>>> list2=list1.copy()
As discussed earlier, = (assignment operator creates an alias) but copy() method creates
a new list list2 is created which the duplicate of an existing list list1. The two lists
copy() list1 and list2 are allocated two different memory location. Any change in the
list1 will not update list2 and vice versa.
>>> list1+=[50] #does not update list2
>>> list2+=[60] #does not update list1
>>> print(list1, list2)
Displays [10, 20, 30, 40, 50] [10, 20, 30, 40, 60]
Removes (deletes) all the elements from a list but the list is not deleted
>>> alist=[10,20,30,40]
>>> alist.clear()
clear()
All the elements are removed (deleted) from the list.
>>> print(alist, len(alist))
Display [] 0 #Empty list => len(alist) is 0 (zero)
Returns count of a value (an element) present in the list
>>> alist=[10,20,30,40,10,20,30,10,20,20]
>>> print(alist.count(20))
count()
Displays 4, because 20 appears 4 times in the list.
>>> print(alist.count(40), alist.count(70))
Displays 1 0, because 10 appears in the list only once and 70 is not in the list.
Returns the lowest positive index of a value (an element) that is present in the list
>>> alist=[10,20,30,40,10,20,30,10,20,20]
>>> print(alist.index(20))
Above statement means look for 20 from the beginning.
Displays 1, because the lowest index of 20 from the left is 1.
>>> print(alist.index(40))
index()
Displays 3, because the lowest index of 40 from the left is 3.
>>> print(alist.index(20,4))
Above statement means look for 20 starting from the 4th index.
Displays 5, because the lowest index of 20 staring from 4th index is 5.
>>> print(alist.index(20,6,9))
Above statement means, look for 20 starting from the 6th index, till 8th index.
FAIPS, DPS Kuwait Page 10 of 18 © Bikram Ally
Python Notes Class XI List
Displays 8, because the lowest index of 20 staring from 6th index is 6.
>>> print(alist.index(100))
Triggers run-time error because 100 is not in the list.
>>> print(alist.index(40,6,9))
Triggers run-time error because 40 is not in the list within that range (6th to 8th).
Inserts a value (an element) into a list
>>> alist=[10,30,50,70]
>>> alist.insert(1,20)
Inserts 20 at the index 1 and elements from index 1 are shifted one index to the right.
>>> print(alist)
Display [10, 20, 30, 50, 70]
>>> alist.insert(10,60)
insert()
60 is appended in the list even when index 10 is out of range.
>>> print(alist)
Display [10, 20, 30, 50, 70, 60]
>>> alist.insert(0,[11,22])
Inserts [11,22] at the index 0, elements from index 0 are shifted one index to the right.
>>> print(alist)
Display [[11, 22], 10, 20, 30, 50, 70, 60]
Deletes an element from a list for a given index
>>> alist=[10,20,30,40,70]
>>> alist.pop()
Function pop() without any parameter deletes the last element from the list. In the IDLE
shell, the above statement will display 70, but in the script mode, nothing will be displayed.
>>> x=alist.pop(1)
Deletes 20 and 20 is stored in the variable x.
>>> print(x)
pop() Displays 20.
>>> print(alist)
Displays [10, 20, 30, 40, 50]
>>> alist.pop(2) #Same as del alist[2]
Function pop()with parameter deletes alist[2] from the list.
>>> print(alist)
Displays [10, 20, 30, 40]
>>> alist.pop(10)
Triggers run-time error because index 10 is out of range.
Deletes the first occurrence of an element, starting from left, if present in a list
>>> alist=[10,20,30,40,20]
>>> alist.remove(30)
Deletes 30 from the list.
>>> print(alist)
Displays [10, 20, 40, 20]
>>> alist.remove(20)
Deletes the first occurrence of 20 (from left) from the list.
remove() >>> print(alist)
Displays [10, 40, 20]
>>> alist.remove(alist[1])
Deletes alist[1] from the list.
>>> print(alist)
Displays [10, 20]
>>> alist.remove(100)
Triggers run-time error because 100 is not in the list.
FAIPS, DPS Kuwait Page 11 of 18 © Bikram Ally
Python Notes Class XI List
Reverses the elements in a list
>>> alist=[10,20,30,40,50]
>>> alist.reverse()
reverse() Reverses the elements in the list permanently.
>>> print(alist)
Displays [50, 40, 30, 20, 10]
Elements of the list are re-arranged in the opposite order.
Sorts a list (elements in a list are re-arranged by default in ascending order)
Built-in function sorted() returns a sorted list, but does not sort the list. Method
sort() will sort the list. Function sort()can be used with list containing either numbers
(int type values and float type values) or strings. If a list contains numbers and strings,
using functions sort() will trigger run-time error.
>>> alist=[50, 20, 40, 10, 30]
>>> alist.sort()
>>> print(alist)
Displays sorted alist in ascending order as [10, 20, 30, 40, 50]
sort() >>> alist=[50, 20, 40, 10, 30]
>>> alist.sort(reverse=True)
>>> print(alist)
Displays sorted alist in descending order as [50, 40, 30, 20, 10]
>>> alist=[66, 22.4, 44, 55.7, 11, 33.9]
>>> alist.sort()
>>> print(alist)
Displays sorted alist in ascending order as [11, 22.4, 33.9, 44, 55.7, 66]
>>> alist=[24, 'TARUN', 'COMP SC', 56.5, 25]
>>> alist.sort()
Triggers run-time error because list containing numbers and strings cannot be sorted.

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.

FAIPS, DPS Kuwait Page 12 of 18 © Bikram Ally


Python Notes Class XI List
alist+=[astr]
#alist.append(astr)
print(alist)
• List containing heterogeneous values
#Program01 - list of numbers Variable alist is an empty list. Statement
alist=[] #alist=list() num=eval(input('Number? '))
n=int(input('No. of elements? ')) Variable num will be int (float) if an integer
for k in range(n): (floating-point) value is inputted. Statement
num=eval(input('Number? ')) alist+=[num] #list.append(num)
alist+=[num] will append value stored in the variable num to
#alist.append(num) the list. So, values in the list will be either an int
print(alist) or a float.
• List containing heterogeneous values
#Program02 - list containing int, str and float
rn=int(input('Roll? '))
na=input('Name? ')
th=float(input('Theo? ')) Using loop one can input / store homogeneous
pr=float(input('Prac? ')) values in a list. To create a list of heterogenous
gr=input('Grade? ') values, values are to be inputted. Values are
alist=[rn, na, th, pr, gr] inputted in rn, na, th, pr, and gr. A list
print(alist) alist is created with rn, na, th, pr and gr.
OR, A list containing int, float and str can only
alist= [ be created by inputting values from the keyboard
int(input('Roll? ')), during the run-time.
input('Name? '),
float(input('Theo? ')),
float(input('Prac? ')),
input('Grade? ')
]
print(alist)

How to store values in a list by using methods from random module:


• List containing homogeneous values Variable alist is an empty list. Function
#Program01 - list of int randint(10,99) generates 2-digit
from random import *
random integers. Statement
n=int(input('Input n? '))
alist+=[randint(10,99)]
alist=[] #alist=list()
appends an element in the list. Instead one can
for k in range(n):
use following code to create a list with n
alist+=[randint(10,99)]
random integer values:
#alist+=[randrange(10,100)]
alist=[randint(10,99) for x in
#alist.append(randrange(10,100))
range(n)]
'''
alist=[randint(10,99) for x in range(n)]
#alist=[randint(10,100) for x in range(n)]
'''
print(alist) Variable alist is an empty list. Function
randint(10,99) generates a floating point value
• List containing homogeneous values
#Program02 - list of float between 10 and 99. Statement
from random import uniform alist+=[uniform(10,99)]
n=int(input('Input n? ')) appends an element in the list. Instead one can use
alist=[] #alist=list() following code to create a list with n random floating-
for k in range(n): point values:
num=uniform(10,99) alist=[uniform(10,99) for x in
alist+=[num] range(n)]
FAIPS, DPS Kuwait Page 13 of 18 © Bikram Ally
Python Notes Class XI List
#alist.append(num)
'''
alist=[uniform(10,99) for x in range(n)]
'''
print(alist)
• List containing homogeneous values Variable alist is an empty list. Statement
#Program03 - list of str astr=chr(6*randint(65,90))
from random import randint creates a string with 6 letters (same letters). Practically
n=int(input('Input n? ')) this kind of code will be of no use. Statement
alist=[] #alist=list() alist+=[astr]
for k in range(n): appends a string astr in the list. Instead one can use
astr=chr(6*randint(65,90))
following code to create a list with n random strings:
alist+=[astr]
alist=[6*chr(randint(65,90)) for x in
#alist.append(astr)
range(n)]
'''
alist=[6*chr(randint(65,90)) for x in range(n)]
'''
print(alist)

• Creating list and displaying list using a loop


#Program04
from random import randint
n=int(input('No. of elements? '))
alist=[randint(10,99) for k in range(n)]
for k in range(n):
print(alist[k]) A list can be displayed using a loop
''' • Using a for / while loop to generate the index of the
OR, elements and then displaying the elements using list
k=0 variable name and the index. Between for loop and
while k<n: while loop, for loop will be a better option because
print(alist[k]) for loop is more compact compared to while loop.
k+=1 • Using a for loop to iterate over list of elements. As
OR, mentioned earlier, in Python, a list is an iterable
for ele in alist: print(ele) object.
'''
• Processing a list
#Program05 – sum of elements
from random import uniform
n=int(input('No. of elements? '))
alist=[round(uniform(10,99),1) for k in range(n)]
s=0
for k in range(n):
s+=alist[k]
print(alist[k], end=' ')
'''
for ele in alist:
s+=ele
print(ele, end=' ')
'''
print('\nSum=',s)
• Processing a list
#Program06 – to find AM, GM, HM of elements
from random import randint
n=int(input('No. of elements? '))
FAIPS, DPS Kuwait Page 14 of 18 © Bikram Ally
Python Notes Class XI List
alist=[randint(10,99) for k in range(n)]
su, pr, sr=0, 1, 0
for k in range(n):
su+=alist[k]
pr*=alist[k]
sr+=1/alist[k]
print(alist[k], end=' ')
'''
for ele in alist:
su+=ele
pr*=ele
sr+=1/ele
print(ele, end=' ')
'''
am=su/n
gm=pr**(1/n)
hm=n/sr
print('\nAM=', am, 'GM=', gm, 'HM=', hm)
• Processing a list
#Program07 – to count number of odd elements and even elements
from random import randint
n=int(input('No. of elements? '))
alist=[randint(10,99) for k in range(n)]
co=ce=0
for k in range(n):
if alist[k]%2==1:
co+=1
else:
ce+=1
print(alist[k], end=' ')
'''
for ele in alist:
if ele%2==1:
co+=1
else:
ce+=1
print(ele, end=' ')
'''
print('\nOdd Elements=',co, 'Even Elements=',ce)
• Processing a list
#Program08 – sum and avg of odd elements and even elements
from random import randint
n=int(input('No. of elements? '))
alist=[randint(10,99) for k in range(n)]
co=ce=so=se=0
for k in range(n):
if alist[k]%2==1:
so+=alist[k]
co+=1
else:
se+=alist[k]
ce+=1
print(alist[k], end=' ')
'''
FAIPS, DPS Kuwait Page 15 of 18 © Bikram Ally
Python Notes Class XI List
for ele in alist:
if ele%2==1:
so+=ele
co+=1
else:
se+=ele
ce+=1
print(ele, end=' ')
'''
avo, ave=so/co, se/ce
print('\nOdd Elements=',co, 'Sum=',so, print('Avgerage=',avo)
print('Even Elements=',ce, 'Sum=',se, print('Avgerage=',ave)
• Processing a list
#Program09 – sum and avg of elements not divisible by 5
from random import randint
n=int(input('No. of elements? '))
alist=[randint(10,99) for k in range(n)]
c=s=0
for k in range(n):
if alist[k]%5!=0: #if alist[k]%5>0:
s+=alist[k]
c+=1
print(alist[k], end=' ')
'''
for ele in alist:
if ele%5!=0: # if ele%5>0:
s+=ele
c+=1
print(ele, end=' ')
'''
avg=s/c
print('\nNumber of Elements not divisible by 5=',c)
print('Sum of Elements not divisible by 5=',s)
print('Avg of Elements not divisible by 5=',avg)
• Processing a list
#Program10 – find max and min stored in a list
from random import uniform
n=int(input('No. of elements? '))
alist=[round(uniform(10,99),2) for k in range(n)]
hi=lo=alist[0]
for k in range(1, n):
if hi>alist[k]:
hi=alist[k]
elif lo<alist[k]:
lo=alist[k]
print(alist[k], end=' ')
'''
for ele in alist:
if hi>ele:
hi=ele
elif lo<ele:
lo=ele
print(ele, end=' ')
'''
FAIPS, DPS Kuwait Page 16 of 18 © Bikram Ally
Python Notes Class XI List
print('\nMax=', hi)
print('\nMin=', lo)
• Processing a list
#Program11 – find max and min stored in a list & their position
from random import uniform
n=int(input('No. of elements? '))
alist=[round(uniform(10,99),2) for k in range(n)]
hi=lo=alist[0]
ph=pl=0
for k in range(1, n):
if hi>alist[k]:
hi=alist[k]
ph=k
elif lo<alist[k]:
lo=alist[k]
pl=k
print(alist[k], end=' ')
print('\nMax=', hi, 'Position=', ph)
print('Min=', lo, 'Position=', pl)
• Processing a list
#Program12 – sum of elements with even index and
#sum of elements with odd index
from random import randint
n=int(input('No. of elements? '))
alist=[randint(100,999) for k in range(n)]
s1=s2=0
for k in range(n):
if k%2==1: #if k%2>0:
s1+=alist[k]
else
s2+=alist[k]
print(alist[k], end=' ')
'''
k=0
while k<n:
if k%2==1: #if k%2>0:
s1+=alist[k]
else
s2+=alist[k]
print(alist[k], end=' ')
k+=1
'''
print('\nSum of elements at odd index=',s1)
print('Sum of elements at even index=',s2)

• 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')
'''

FAIPS, DPS Kuwait Page 18 of 18 © Bikram Ally


Python Notes Class XI Tuple
In Python a tuple is special type of variable used to represent many values under one variable name in the
RAM. A variable of fundamental data type like int or float or str will store only one value. A Python
tuple will store many values. A tuple will be a collection or sequence, almost similar to a list. A tuple
may be homogenous collection or it may be a heterogenous collection. It may seem list and tuple are
similar. But no, list is mutable whereas tuple is immutable. A tuple is created in the following way:

tuplename=(value1, value2, value3, …)


OR,
tuplename=value1, value2, value3, …

>>> tup1=(100, 200, 300, 400, 500)


>>> tup2=24.3, 46.5, 55.5, 68.7, 82.9
>>> tup3='NEW DELHI', 'MUMBAI', 'KOLKATA', 'CHENNAI', 'BENGALURU'
>>> tup4=(1040, 'SANDEE GARG', 'MANAGER', 150000.0)
>>> tup5=() #tup5=tuple()

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.

0 1 2 3 4 A tuple with 5 elements, elements are


tup1 100 200 300 400 500 assigned indices 0, 1, 2, 3, 4 or they are
-5 -4 -3 -2 -1 assigned indices -1, -2, -3, -4, -5.

>>> 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

>>> tup=(1040, 'SANDEE GARG', 'MANAGER', 150000.0)


>>> for k in range(4): print(tup[k],end=' ')
Displays the tuple left to right: 1040 SANDEE GARG MANAGER 150000.0
>>> for k in range(1,5): print(tup[-k],end=' ')
Displays the tuple right to left: 150000.0 MANAGER SANDEE GARG 1040
>>> for ele in tup: print(ele,end=' ')
Displays the tuple left to right: 1040 SANDEE GARG MANAGER 150000.0
FAIPS, DPS Kuwait Page 1 of 9 © Bikram Ally
Python Notes Class XI Tuple
>>> print(tup[4])
Displays run-time error: tuple index out of range since there are 4 elements in the tuple tup and
positive index of the last element is 3.
>>> print(tup[-5])
Displays run-time error: tuple index out of range since tuple with 4 elements in the tuple tup, first
negative index is -4.

Using operators and keyword del with typle


Creates a new tuple
>>> student=(24, 'TARUN', 56, 25, 81, 'B1')
>>> print(student)
=
Displays student=(24, 'TARUN', 56, 25, 81, 'B1')
>>> student=() #student=tuple() creates empty tuple
Displays (), an empty tuple is displayed
Joins to two or more tuples (concatenates two or more tuples)
>>> tup1=(10,20,30)
+ >>> tup2=tup1+(40,50)
>>> print(tup2)
Displays (10, 20, 30, 40, 50)
Updates an existing tuple by appending elements present in another tuple
>>> tup1, tup2=(10, 20, 30), (40,50,60)
+= >>> tup1+=tup2
>>> print(tup1)
Displays (10, 20, 30, 40, 50, 60)
Replicates a tuple
>>> tup1=(10, 20, 30)
>>> tup2=2*tup1
New tuple tup2 is created by duplicating values present in tuple tup1.
>>> print(tup2)
Displays (10, 20, 30, 10, 20, 30)
>>> tup2=0*tup1
*
>>> print(tup2)
Displays (), an empty tuple is displayed
>>> tup2=-3*tup1
>>> print(tup2)
Displays (), an empty tuple is displayed
>>> tup2=1.6*tup1
Triggers run-time error.
Updates an existing tuple by replicating values stored in the tuple
>>> tup=(10, 20, 30)
>>> tup*=3
The tuple tup is updated by triplicating values present in the tuple tup.
>>> print(tup)
Displays (10, 20, 30, 10, 20, 30, 10, 20, 30)
>>> tup*=-4
*= >>> print(tup)
Displays (), an empty list is displayed
>>> tup1, tup2=(10, 20, 30), (40, 50, 60)
>>> tup1*=0
>>> print(tup1)
Displays (), an empty list is displayed
>>> tup2*=2.8
Triggers run-time error.
FAIPS, DPS Kuwait Page 2 of 9 © Bikram Ally
Python Notes Class XI Tuple
Deletes a tuple
>>> tup=(10, 20, 30)
del >>> del tup
>>> print(tup)
Triggers run-time error because the tuple tup has been deleted from the memory.
Check whether an element is a member of tuple
>>> tup=(10, 20, 30)
>>> print(20 in tup)
in
Displays True since 20 is present in the tuple tup
>>> print(40 in tup)
Displays False since 40 is not present in the tuple tup
Checks whether two tuples are equal
>>> atup=(10, 20, 30)
>>> btup=(10, 20, 30)
>>> ctup=(20, 10, 30)
== >>> print(atup==btup)
Displays True since corresponding elements of atup and btup are equal
>>> print(atup==ctup)
Displays False since corresponding elements of atup and btup are not equal
Two tuples are compared by checking the values present in the corresponding elements.
Checks whether two lists are not equal
>>> atup=(10, 20, 30)
>>> btup=(10, 20, 30)
>>> ctup=(20, 10, 30)
!=
>>> print(atup!=btup)
Displays False since corresponding elements of atup and btup are equal
>>> print(atup!=ctup)
Displays True since corresponding elements of atup and btup are not equal
Checks whether one list is greater than or equal to second list
>>> atup, btup=(10, 20, 30), (10, 20, 30)
>>> ctup=(20, 10, 30)
>>> print(atup>btup)
Displays False since corresponding elements of atup and btup are equal
>>> print(atup>=btup)
Displays True since corresponding elements of atup and btup are equal
>,>= >>> print(atup>ctup)
Displays False since 10 of atup is less than 20 of ctup
>>> print(atup>=ctup)
Displays False since 10 of atup is less than 20 of ctup
If the two elements cannot be compared using > or <, then an error will be triggered.
>>> a, b=(10, 'AB'), (10, 20)
>>> print(a>b)
Triggers an error.
Checks whether one list is less than or equal to second list
>>> atup, btup=(10, 20, 30), (10, 20, 30)
>>> ctup=(20, 10, 30)
<,<= >>> print(atup<btup)
Displays False since corresponding elements of atup and btup are equal
>>> print(atup<=btup)
Displays True since corresponding elements of atup and btup are equal

FAIPS, DPS Kuwait Page 3 of 9 © Bikram Ally


Python Notes Class XI Tuple
>>> print(atup<ctup)
Displays True since 10 of atup is less than 20 of ctup
>>> print(atup<=ctup)
Displays False since 10 of atup is less than 20 of ctup
If the two elements cannot be compared using > or <, then an error will be triggered.
>>> a, b=(10, 'AB'), (10, 20)
>>> print(a>b)
Triggers an error.

Built-in functions for tuple data type


print()
As discussed earlier, function print() displays the entire tuple on the screen from left to right.

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=('EE', 'CC', 'AA', 'BB', 'DD')


>>> sorted(tup)
Displays ['AA', 'BB', 'CC', 'DD', 'EE']

>>> 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)

>>> tup=('EE', 'CC', 'AA', 'BB', 'DD')


>>> sorted(tup, reverse=True)
Displays ['EE', 'DD', 'CC', 'BB', 'AA']

>>> tup=('EE', 10, 'AA', 20, 'DD')


>>> sorted(tup)
Triggers run-time error.

FAIPS, DPS Kuwait Page 4 of 9 © Bikram Ally


Python Notes Class XI Tuple
Two methods from tuple class
Returns count of a value present in a tuple (same as count() method of list)
>>> tup=(10,20,30,40,10,20,30,10,20,20)
>>> print(tup.count(20))
Displays 4, because 20 appears in the tuple 4 times.
count()
>>> print(tup.count(40))
Displays 1, because 10 appears in the tuple only once.
>>> print(tup.count(70))
Displays 0, because 70 is not present in the tuple.
Returns the lowest index of a value that is present in the tuple (same as index()method
of list)
>>> tup=(10,20,30,40,10,20,30,10,10,20)
>>> print(tup.index(20))
Displays 1, because lowest index of 20 is 1
>>> print(tup.index(20,4))
index() Displays 5, starting from 4th index, value 20 appear in the 5th index
>>> print(tup.index(10,5,9))
Displays 7, starting from 5th index, value 10 appear in the 7th index
>>> print(tup.index(100))
Displays run-time error because 100 is not in the tuple.
>>> print(tup.index(40,5,9))
Displays run-time error because 40 is not in the tuple within index range of 5 to 8
Important points to remember regarding creating a tuple:
>>> tup=(10,20,30) #tup is tuple with 3 elements - 10, 20, 30
>>> tup=40,50,60 #tup is tuple with 3 elements – 40, 50, 60
>>> tup=200 #tup is an int type variable and not a tuple
>>> tup=(100,) #tup is tuple with 1 element - 100
>>> tup=(100) #tup is an int type variable and not a tuple
>>> tup=tuple([10,20]) #tup is a tuple created from a list
>>> alist=list((40,50)) #alist is list created from a tuple

How to store values in a tuple


• Tuple containing homogeneous values
#Program01 - tuple of int
from random import randint
tup=() #tup=tuple()
n=int(input('No. of elements? '))
for k in range(n): tup+=(randint(10,99),)
print(tup)
Note: To store random floating point values in the tuple (for the three Python programs given above),
use random(uniform(10,99),1)) to generate floating point values (2 digits before decimal
point and 1 digit after the decimal point)

• Tuple containing homogeneous values


#Program02 - tuple of int
from random import randint
n=int(input('No. of elements? '))
tup=tuple([randint(10,99) for k in range(n)])
print(tup)
Note: To store random floating point values in the tuple (for the two Python programs given above),
use random(uniform(10,99),1)) to generate floating point values (2 digits before decimal
point and 1 digit after the decimal point)

FAIPS, DPS Kuwait Page 5 of 9 © Bikram Ally


Python Notes Class XI Tuple
• Tuple containing homogeneous values
#Program03 – creating tuple by inputting values
n=int(input('No. of elements? '))
tup=()
for k in range(n):
item=int(input('Integer? '))
#item=float(input('Number? '))
#item=input('String? ')
#item=eval(input('Number? '))
tup+=(item,)
print(tup)

• Tuple containing heterogeneous values


#Program04 - tuple of int, str and float
rn=int(input('Roll? '))
na=input('Name? ')
cl=input('Class? ')
su=input('Subject? ')
th=float(input('Theo? '))
pr=float(input('Prac? '))
gr=input('Grade? ')
tup=(rn, na, cl, su, th, pr, th+pr, gr)
#tup=rn, na, cl, su, th, pr, th+pr, gr
'''
tup= (
int(input('Roll? ')),
input('Name? '),
input('Class? '),
input('Subject? '),
float(input('Theo? ')),
float(input('Prac? ')),
gr=input('Grade? ')
)
'''
print(tup)

• Creating tuple and displaying tuple using a loop


#Program05
from random import randint
n=int(input('No. of elements? '))
tup=()
for k in range(n):
tup+=(randint(10,99),)
for k in range(n):
print(tup[k], end=' ')
#Or, for ele in tup: print(ele, end=' ')
'''
k=0
while k<n:
print(tup[k], end=' ')
k+=1
'''

FAIPS, DPS Kuwait Page 6 of 9 © Bikram Ally


Python Notes Class XI Tuple
A tuple is an immutable type data. Characteristics of immutable data type:
1. Cannot update an element of a tuple(str)
>>> tup=(10,20,60,40,50)
>>> tup[2]=30 #Displays run-time error message
>>> print(tup)
Displays tuple as (10, 20, 60, 40, 50)

2. An element of a tuple(str) cannot be deleted by using del


>>> tup=(10,20,60,40,50)
>>> del tup[2] #Displays run-time error message
>>> print(tup)
Displays tuple as (10, 20, 60, 40, 50)

3. A tuple cannot be sorted directly


As discussed earlier, a tuple cannot be sorted directly
>>> tup=(40,20,30,50,10)
>>> sorted(tup)
Displays the tuple tup as a list sorted in ascending order [10, 20, 30, 40, 50]
>>> sorted(tup, reverse=True)
Displays the tuple tup as a list sorted in descending order [50, 40, 30, 20, 10]
>>> print(tup)
Displays the unsorted tup as (40,20,30,50,10)
But a tuple can be sorted indirectly either using sorted() or using Python code / function
>>> tup=(40,20,30,50,10)
>>> tup=tuple(sorted(tup))
>>> print(tup)
Displays sorted tup as (10, 20, 30, 40, 50)

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)

Differences between list and tuple


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

FAIPS, DPS Kuwait Page 9 of 9 © Bikram Ally


Python Notes Class XI String
In Python a string is a collection of either ASCII characters or Unicode characters stored one variable name in
the RAM. However, string is a fundamental data type like int or float. A string is also called sequence, and
iterable type. A string similar to tuple rather than list since string is an immutable type. A string is created in the
following way:

strname='Kuwait' #creates a non-empty string


OR,
strname="Kuwait" #creates a non-empty string
OR,
strname='' #creates an empty string
OR,
strname="" #creates an empty string
OR,
strname='''''' #creates an empty string
OR,
strname="""""" #creates an empty string
OR,
strname=str() #creates an empty string

>>> str1='49 South Street, Ahamdi-61010, Kuwait'


>>> str2='शभु प्रभात'
>>> str3='সুপ্রভাত'

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 (""").

Suppose str1 is string containing 'MANGO'

0 1 2 3 4 A string with 5 characters, characters


str1 M A N G O are assigned indices 0, 1, 2, 3, 4 or they
-5 -4 -3 -2 -1 are assigned indices -1, -2, -3, -4, -5.

>>> 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.

Using operators and keyword del with type


Creates a new string but cannot update a value stored in the string
>>> str1, str2='India, New Delhi', 'SONDAY'
>>> print(str1)
=
Displays India, New Delhi
>>> str1[1]='U'
Displays run-time error because the string is an immutable type.
Concatenate two or more strings
>>> str1='India,'+' New'+' Delhi'
+ >>> print(str1)
Displays India, New Delhi
Updates an existing string by concatenating another string
>>> str1='New'
>>> print(str1, id(str1))
+= Displays New, 2273046316016
>>> str1+=' Delhi'
>>> print(str1, id(str1))
Displays New Delhi 2273041112864 since string is an immutable type, ID changes
Replicate a string
>>> str1='Kuwait'
>>> print(str1*3)
Displays KuwaitKuwaitKuwait
>>> print(str1*0)
* Displays an empty string
>>> print(str1*-3)
Displays an empty string
>>> print(str1*2.5)
Triggers an error
A string can be multiplied with an integer value.
Updates an existing string by replicating values stored in the string
>>> str1='Delhi'
>>> str1*=3
*= The string str1 is updated triplicating values stored in the string.
>>> print(str1)
Displays DelhiDelhiDelhi
Deletes a string
>>> str1='Mangaf'
>>> del str1
>>> print(str1)
del
Displays run-time error because the string str1 has been deleted from the memory.
>>> str1='Mangaf'
>>> del str1[2]
Displays run-time error because the string is an immutable type.
Check whether a sub-string is a member of tuple
>>> str1='MANGAF'
>>> print('MAN' in str1, 'G' in str1)
in
Displays True True since 'ANG' and 'G' are present in the string str1
>>> print('GN' in str1)
Displays False since 'GN' is present in the string str1

FAIPS, DPS Kuwait Page 2 of 10 © Bikram Ally


Python Notes Class XI String
Built-in functions for string data type
print()
As discussed earlier, function print() displays string on the screen without the delimiters.

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

Methods from string objects:


Function name Use of the function of the function
Returns a string converted to uppercase. Only lowercase is converted to uppercase.
address='GH-14/783,Paschim Vihar,New Delhi-110087'
upper()
print(address.upper())
Displays GH-14/783,PASCHIM VIHAR,NEW DELHI-110087
Returns a string converted to lowercase. Only uppercase is converted to lowercase.
address='GH-14/783,Paschim Vihar,New Delhi-110087'
lower(), print(address.lower())
casefold() Displays gh-14/783,paschim vihar,new delhi-110087
print(address.casefold())
Displays gh-14/783,paschim vihar,new delhi-110087
Checks whether the string contains uppercase. Returns True if str does not contains any
lowercase. Returns False if a string contains lowercase.
isupper() a,b,c='FAIPS', 'FaIpS', 'PO BOX-9951'
print(a.isupper(), b.isupper(), c.isupper())
Displays True False True
Checks whether the string contains lowercase. Returns True if str does not contains any
uppercase. Returns False if a string contains uppercase.
islower() a,b,c='faips', 'fAiPs', 'po box-9951'
print(a.islower(), b.islower(), c.islower())
Displays True False True
Checks whether the string contains only alphabets (uppercase and lowercase). Returns True
isalpha() if a string contains either uppercase or lowercase or both. Returns False if a string does not
contain any digits or any special characters.
a,b,c,d='DPS','dps','DpS','PO Box-9951'
FAIPS, DPS Kuwait Page 3 of 10 © Bikram Ally
Python Notes Class XI String
print(a.isalpha(),b.isalpha(),c.isalpha(),d.isalpha())
Displays True True True False
Checks whether the string contains digit. Returns True if a string contains only digit. Return
False if a string contains either alphabets or special characters or both.
isdigit() a,b,c,d='1234','FLAT24','flat24','Flat-24'
print(a.isdigit(),b.isdigit(),a.isdigit(),d.isdigit()) Displays
True False False False
Checks whether the string contains either alphabet or digit or both. Returns True if a string
contains either alphabet or digit or both. Return False if a string contains special characters.
isalnum() a,b,c,d='Flat24','FLAT24','flat24','Flat-24'
print(a.isdigit(),b.isdigit(),a.isdigit(),d.isdigit()) Displays
True True True False
Checks for whitespace characters space(' '), tab('\t') or new line('\n')
present in a string. A whitespace character is not visible on the screen. Returns True if a
isspace() string contains only whitespace character(s).
a,b,c,d=' ',' \t',' \t \n', 'New - Delhi'
print(a.isspace(),b.isspace(),a.isspace(),d.isspace()) Displays
True True True False
Returns a string by converts the first character of a string to uppercase and rest of the
alphabetic characters are converted to lowercase.
str1,str2,str3='NEW DELHI','new delhi','NeW dElHi'
print(str1.capitalize(), str2.capitalize(), end=' ')
capitalize() print(str3.capitalize())
Displays New delhi New delhi New delhi
>>> city='*NEW*delhi'
>>> print(city.capitalize())
Displays *new*delhi
Return a string by converting first character of every word (sub string separated by white-
space character(s)) present in a string converted to uppercase, rest of the alphabetic
characters in the word will be converted to lowercase.
str1,str2,str3='NEW DELHI','new delhi','NeW dElHi'
title() print(str1.title(),str2.title(), str3.title())
Displays New Delhi New Delhi New Delhi
>>> city='*NEW*delhi'
>>> print(city.title())
Displays *New*Delhi
Exactly same as count() method of list and it returns occurrence of a sub-string present
within big string. Returns 0 if the sub-string could not be located within the big string.
s='NEW DELHI'
count() print(s.count('E'),s.count('DEL'),s.count('IN'))
Displays 2 1 0
print(s.count('E',4),s.count('W',4,9))
Displays 1 0
Almost similar to index() method list and it returns lowest non-negative index of a sub-
string present within another string. Unlike index() method of list, it returns -1
when the sub-string could not be located in the string.
s='NEW DELHI'
print(s.find('E'),s.find('DEL'),s.find('IN'))
find()
Displays 1 4 -1
print(s.find('E',4),s.find('E',6))
Displays 5 -1
print(s.find('E'),s.find('E',4),s.find('E',6,10))
Displays 1 5 -1

FAIPS, DPS Kuwait Page 4 of 10 © Bikram Ally


Python Notes Class XI String
Exactly similar to index() method list and it returns lowest non-negative index of a sub-
string present within a big string. If a sub-string is not present within the big string, it will
trigger a run-time error.
s='NEW DELHI'
print(s.index('E'),s.index('DEL'),s.index('E',4))
index()
Displays 1 4 5
print(s.index('D',2,7))
Displays 4
print(s.index('Z'))
Triggers a run-time error
Removes all the white-space characters from the both ends of a string.
s=' Mangaf, Kuwait '
strip()
print(s.strip())
Displays Mangaf, Kuwait removing white space characters from both ends
Removes all the white-space characters from the left (beginning) of a string.
s=' Mangaf, Kuwait '
lstrip()
print(s.strip())
Displays Mangaf, Kuwait removing white space characters from left
Removes all the white-space characters from the right (end) of a string.
s=' Mangaf, Kuwait '
rstrip()
print(s.strip())
Displays Mangaf, Kuwait removing white space characters from right
Creates a list containing sub-string from a big string separated by white space character(s)
by default or separated by a delimiter. Delimiter is not included in the list.
s='Sun Mon Tue Wed Thu Fri Sat'
wlist=s.split()
print(wlist)
Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] since parameter is missing
from split() method, the default delimiter is white-space
s='Sun,Mon,Tue,Wed,Thu'
split()
print(s.split(','))
Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu']
print(s.split(',',3))
Displays ['Sun', 'Mon', 'Tue', 'Wed,Thu']
s='FAIPS,DPS,Kuwait'
print(s.split('*'))
Displays ['FAIPS,DPS,Kuwait'] since delimited '*' is missing, list contains only
one element, the entire string
The partition() method searches for a specified sub-string, and splits the big string into a
tuple containing three elements. The first element contains the part before the specified
string. The second element contains the specified string. The third element contains the part
after the string.
s='MangafFahaheelAhmadi'
alist=s.partition('Fahaheel')
print(alist)
Displays ('Mangaf', 'Fahaheel', 'Ahmadi')
partition() alist=s.partition('Mangaf')
print(alist)
Displays ('', ' MangafFahaheel', 'Ahmadi')
Print(s.partition('Ahmadi'))
Displays ('MangafFahaheel', 'Ahmadi', '')
alist=s.partition('Delhi')
print(alist)
Displays ('MangafFahaheelAhmadi', '', '')
FAIPS, DPS Kuwait Page 5 of 10 © Bikram Ally
Python Notes Class XI String
The join() method takes all items (all items must be string) from an iterable (list / tuple /
dictionary) and joins them into one string. A string must be specified as the separator.
alist=['10','ASHOK','89.0']
blist=('21','ROOPA','75.5')
join()
astr=','.join(alist) #',' is the separator
bstr='~'.join(blist) #'~' is the separator
print(astr, bstr)
Displays 10,ASHOK,89.0 21~ROOPA~75.5
The replace() method replaces a specified phrase with another specified phrase.
s='ABCD , 1234 , efgh , {()}'
t=s.replace(' , ', '<->')
replace() print(t)
Displays ABCD<->1234<->efgh<->{()}
By default replaces all occurrence of ' , ' with '<->'
The startswith() method returns True if the string starts with the specified value, otherwise
False.
s='Hello, Python'
startswith() print(s.startswith('Hell'), s.startswith('Python'))
Displays True False
print(s.startswith('Python', 7))
Displays True
The endswith() method returns True if the string ends with the specified value, otherwise
False.
s='Hello, Python'
endswith() print(s.endswith('Hell'), s.endswith('Python'))
Displays False True
print(s.endswith('Hell',0))
Displays True

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

#Obtain a new string by converting an inputted string into uppercase


astr=input('Input a string? ')
bstr=''
for ch in astr:
if 'a'<=ch<='z':
ch=chr(ord(ch)-32)
bstr+=ch
print('Uppercase string=',bstr)
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)):
ch=astr[x]
if 'a'<=ch<='z':
ch=chr(ord(ch)-32)
bstr+=ch
print('Uppercase string=',bstr)

#Obtain a new string by converting an inputted string into lowercase


astr=input('Input a string? ')
bstr=''
for ch in astr:
if 'A'<=ch<='Z':
ch=chr(ord(ch)+32)
bstr+=ch
print('Lowercase string=',bstr)
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)):
ch=astr[x]
if 'A'<=ch<='Z':
ch=chr(ord(ch)+32)
bstr+=ch
print('Lowercase string=',bstr)

#Obtain a new string by toggling the case of letters present in the


#inputted string
astr=input('Input a string? ')
bstr=''
for ch in astr:
if 'a'<=ch<='z': ch=chr(ord(ch)-32)
elif 'A'<=ch<='Z': ch=chr(ord(ch)+32)
bstr+=ch
print('Toggled string=',bstr)
OR,
astr=input('Input a string? ')
FAIPS, DPS Kuwait Page 7 of 10 © Bikram Ally
Python Notes Class XI String
bstr=''
for x in range(len(astr)):
ch=astr[x]
if 'a'<=ch<='z': ch=chr(ord(ch)-32)
elif 'A'<=ch<='Z': ch=chr(ord(ch)+32)
bstr+=ch
print('Toggled string=',bstr)

#Obtain a new string by reversing the characters present in the inputted


#string
astr=input('Input a string? ')
bstr=''
for ch in astr: bstr=ch+bstr
print('Reversed String=', bstr)
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)): bstr=astr[x]+bstr
print('Reversed String=', bstr)

#Check whether the inputted string is Palindrome or not


astr=input('Input a string? ')
bstr=''
for ch in astr: bstr=ch+bstr
if astr==bstr:
print(astr, 'Palindrome')
else:
print(astr, 'Not Palindrome')
OR,
astr=input('Input a string? ')
bstr=''
for x in range(len(astr)): bstr=astr[x]+bstr
if astr==bstr:
print(astr, 'Palindrome')
else:
print(astr, 'Not Palindrome')
OR,
astr=input('Input a string? ')
n=len(astr)
for x in range(n//2):
if astr[x]!=astr[-x-1]:
print(astr, 'Not Palindrome')
break
else:
print(astr, 'Palindrome')

#Count uppercase, lowercase, digits and special characters


astr=input('Input a string? ')
uc==lc=dc=sc=0
for ch in astr:
if 'A'<=ch<='Z': uc+=1
FAIPS, DPS Kuwait Page 8 of 10 © Bikram Ally
Python Notes Class XI String
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('Special Characters=', sc)
OR,
astr=input('Input a string? ')
uc==lc=dc=sc=0
for x in range(len(astr)):
ch=astr[x]
if 'A'<=ch<='Z': uc+=1
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('Special Characters=', sc)

#Count uppercase, lowercase, digits white-space characters and special


#characters (excluding white-space characters
astr=input('Input a string? ')
uc=lc=dc=wc=sc=0
for ch in astr:
if 'A'<=ch<='Z': uc+=1
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
elif ch in ' \t\n': wc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('White-space Characters=', wc)
print('Special Characters=', sc)
OR,
astr=input('Input a string? ')
uc=lc=dc=wc=sc=0
for x in range(len(astr)):
ch=astr[x]
if 'A'<=ch<='Z': uc+=1
elif 'a'<=ch<='z': lc+=1
elif '0'<=ch<='9': dc+=1
elif ch in ' \t\n': wc+=1
else: sc+=1
print('Uppercase=', uc)
print('Lowercase=', lc)
print('Digit=', dc)
print('White-space Characters=', wc)
print('Special Characters=', sc)
FAIPS, DPS Kuwait Page 9 of 10 © Bikram Ally
Python Notes Class XI String

#Counting words in an inputted string


astr=input('Input a string? ')
wlist=astr.split()
c1=c2=c3=c4=c5=c6=c7=0
for word in wlist:
if len(word)==4: c1+=1
if len(word)>4: c2+=1
if len(word)<4: c3+=1
if 'A'<=word[0]<'Z' or 'a'<=word[0]<='z':
#if word[0].isalpha():
if word[0] in 'AEIOUaeiou': c4+=1
else: c5+=1
if 'A'<=word[-1]<'Z' or 'a'<=word[-1]<='z':
#if word[-1].isalpha():
if word[-1] in 'AEIOUaeiou': c6+=1
else: c7+=1
print('Number of words with exactly 4 characters=', c1)
print('Number of words with more than 4 characters=', c2)
print('Number of words with less than 4 characters=', c3)
print('Number of words starting with vowel=', c4)
print('Number of words not starting with vowel=', c5)
print('Number of words ending with vowel=', c6)
print('Number of words not ending with vowel=', c7)

#Counting words containing at least two vowels


astr=input('Input a string? ')
wlist=astr.split()
wc=0
for word in wlist:
vc=0
for ch in word:
if ch in 'AEIOUaeiou': vc+=1
if vc>1: wc+=1
print('Number of words containing at least 2 vowels=', wc)

#Counting words containing at least three consonants


astr=input('Input a string? ')
wlist=astr.split()
wc=0
for word in wlist:
cc=0
for ch in word:
if 'A'<=ch<='Z' or 'a'<=ch<='z':
if ch not in 'AEIOUaeiou': cc+=1
if cc>2: wc+=1
print('Number of words containing at least 3 consonants=', wc)

FAIPS, DPS Kuwait Page 10 of 10 © Bikram Ally


Python Notes Class XI Dictionary
A dictionary is a collection of key:pair values. A key:pair is also called an element of the dictionary. All
the key:pair values (elements) in the dictionary are enclosed within {}.. The value on the left-hand side of
the colon (:) is the key. A key is immutable type like int or float or str or bool or complex or tuple. Key
can either be a constant or a variable. The value on the right-hand side of the colon (:) is the value for the
key. Value for the value can either be a constant or a variable or an expression. A value for the key can
either be mutable type or an immutable type. A dictionary is a mutable type. In a dictionary's key acts
like an index for every element present in the dictionary. A dictionary is an iterable type and mapping type
but not a sequence type. How to create a dictionary?

dictname={key1:value1, key2:value2, key3:value3,…}

>>> d1={1:1011, 2:'ABHIJIT', 3:78000.0}


>>> d2={1.5:1012, 2.5:'SUNIL', 3.5:75000.0}
>>> d3={'eno':1013, 'name':'KARAN', 'bsal':77000.0}
>>> eno, name, bsal=1014, 'DEEPAK', 76000.0
>>> d4={'eno':eno, 'name':name, 'bsal':bsal, 'hra':0.2*bsal}
>>> co,na,bs='code','name','bsal'
>>> code,name,bsal=1027,'RADHIKA SINHA',156000.0
>>> d5={co:code, na:name, bs:bsal}
>>> d6={} #d6=dict()

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([])

To append new key(s) in a dictionary


1. Add a new key using = operator
>>> stu={'rn':24, 'na':'TARUN', 'th':45}
>>> stu['th']=47 #updates key 'th'
>>> stu['pr']=25 #appends a new key 'pr':25
>>> stu['tt']=72 #appends a new key 'th':72
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':25, 'tt':70}
OR,

FAIPS, DPS Kuwait Page 2 of 9 © Bikram Ally


Python Notes Class XI Dictionary
Append a new keys using dictionary method update()
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> stu.update({'pr':25, 'tt':72}) #appends new keys 'pr' and 'tt'
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':25, 'tt':72}

2. Appending a new dictionary to an existing dictionary


We can add more than one keys by using the method described in 1. But we can use dictionary method
update() to add more than one keys in a dictionary in one go.
>>> stu={'rn':24, 'na':'TARUN'}
>>> print(stu)
Displays {'rn':24, 'na':'TARUN'}
>>> stu.update({'th',47, 'pr',27, 'tt',72})
Add new keys 'th':45, 'pr':27 and 'tt':72 in the dictionary stu.
To add more than one keys, another dictionary is passed as a parameter to update() function.
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':45, 'pr':27, 'tt':72}
OR,
>>> stu={'rn':24, 'na':'TARUN'}
>>> marks={'th':47, 'pr':27, 'tt':72}
>>> stu.update(marks)
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':45, 'pr':27, 'tt':72}

Using operators, keywords and built-in functions used with dictionary:


Creates a new dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47.0}
= >>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47.0}
>>> stu={} #stu=dict() creates an empty dictionary
Updating a key in a dictionary the exists
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
= >>> stu['th']=50
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':50}
A new key is appended to a dictionary if the key does not exist
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
= >>> stu['pr']=24
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':24}
Creates a new dictionary which is an alias of an existing dictionary
>>> stu1={'rn':24, 'na':'TARUN'}
>>> stu2=stu1
The dictionary stu2 is created as an alias of stu1 since dictionary is mutable type. Since
dictionaries stu1 and stu2 share same memory location, any change in stu1 will
update stu2 and vice-versa.
=
>>> stu1['th']=50 #New key 'th' is appended to stu2
>>> stu2['th']=53 #Updates 'th' of stu1
>>> print(stu1)
Displays {'rn':24, 'na':'TARUN', 'th':53}
>>> print(stu2)
Displays {'rn':24, 'na':'TARUN', 'th':53}

FAIPS, DPS Kuwait Page 3 of 9 © Bikram Ally


Python Notes Class XI Dictionary
Deletes an element or elements from a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':27, 'tt':74}
del >>> del stu['pr'], stu['tt'] #delete keys 'pr','tt'
>>> print(stu)
Displays {'na':'TARUN', 'th':47}
Deletes a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
del >>> del stu
>>> print(stu)
Syntax error detected because the dictionary stu has been deleted from the memory
Checks whether a key is in a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print('na' in stu)
in
Displays True, since key 'na' is in the dictionary stu
>>> print('pr' in stu)
Displays False, since key 'pr' is not in the dictionary stu
Returns the length of a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
len()
>>> print(len(stu))
Displays 3, since there are 3 elements (3 pairs) in the dictionary stu
Method min() returns the lowest / smallest key in the dictionary
Method max() returns the highest / largest key in the dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print(min(stu), max(stu))
Displays na th since from the list of keys ['rn', 'na', 'th'], 'na' is the lowest
value and 'th' is the highest value.
>>> stu={1:24, 2:'TARUN', 3:47}
>>> print(min(stu), max(stu))
Displays 1 3
max() >>> stu={1.0:24, 2.0:'TARUN', 3.0:47}
min() >>> print(min(stu), max(stu))
Displays 1.0 3.0
>>> stu={1:24, 2.0:'TARUN', 3:47, 4.0:26}
>>> print(min(stu), max(stu))
Displays 1 4.0
>>> stu={'1':24, 2:'TARUN', 3.0:47}
>>> print(min(stu))
Triggers run-time error since number and string cannot be compared using > or <
>>> print(max(stu))
Triggers run-time error since number and string cannot be compared using > or <
Returns the sum of the keys in the dictionary
>>> stu={1:24, 2:'TARUN', 3:47}
>>> print(sum(stu))
Displays 6
>>> stu={1.0:24, 2.0:'TARUN', 3.0:47}
>>> print(sum(stu))
sum()
Displays 6.0
>>> stu={1:24, 2.0:'TARUN', 3:47, 4.0:26}
>>> print(sum(stu))
Displays 10.0
>>> stu={1:24, '2':'TARUN', 3.0:47}
>>> print(sum(stu))

FAIPS, DPS Kuwait Page 4 of 9 © Bikram Ally


Python Notes Class XI Dictionary
Triggers run-time error since numbers and strings cannot be added
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print(sum(stu))
Triggers run-time error since strings cannot be added
Returns the keys as a sorted list
>>> stu={2:24, 1:'TARUN', 4:47, 3:27}
>>> print(sorted(stu))
Displays [1, 2, 3, 4]
>>> stu={2.1:24, 1.2:'TARUN', 4.5:47, 3.4:27}
>>> print(sorted(stu))
Displays [1.2, 2.1, 3.4, 4.5]
>>> stu={1:24, 2.0:'TARUN', 3:47, 4.0:26}
sorted()
>>> print(sorted(stu))
Displays [1, 2.0, 3, 4.0]
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print(sorted(stu))
Displays ['na', 'rn', 'th']
>>> stu={1:24, '2':'TARUN', 3.0:47}
>>> print(sorted(stu))
Triggers run-time error since number and string cannot be compared using > or <
Displays a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
print()
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47}

Methods from dictionary


Removes all elements (pairs) from a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> stu.clear()
clear()
Removes / deletes all the keys from the dictionary.
>>> print(stu, len(stu))
Displays {} 0 #stu is empty => len(stu) is 0 (zero)
Creates a duplicate of an existing dictionary
>>> stu1={'rn':24, 'na':'TARUN', 'th':47}
>>> stu2=stu1.copy()
The dictionary stu2 is a copy of the dictionary stu1. Dictionaries stu1 and stu2
share two different memory locations. Updating stu1 will not update stu2 and
copy() vice-versa.
>>> stu1['pr']=28 #New key 'pr' is appended to stu1
>>> print(stu1)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu2)
Displays {'rn':24, 'na':'TARUN', 'th':47}, stu2 is not updated
Returns value for the key present in the dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28, 'tt':75}
>>> print(stu.get('tt')) #same as print(stu['tt'])
Displays 75 since value for the key 'tt' is 75
get() >>> print(stu.get('gr'))
Displays None since the key 'gr' is not present in stu.
>>> print(stu['gr'])
Triggers run-time error since key 'gr' is not present in stu.
>>> print(stu.get('gr', 'C1'))

FAIPS, DPS Kuwait Page 5 of 9 © Bikram Ally


Python Notes Class XI Dictionary
Displays C1 since the key 'gr' is not present in stu but returns the default value
>>> print(stu['th'])
Displays 47 since value for the key 'th' is 47
>>> print(stu.get('tt', 100))
Displays 75 since the key 'tt' is present in stu and second parameter is ignored
Returns keys stored in a dictionary as an iterable object
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> stukeys=stu.keys()
>>> print(stukeys)
Displays dict_keys(['rn', 'na', 'th'])
>>> stu['pr']=28
>>> print(stukeys)
Displays dict_keys(['rn', 'na', 'th', 'pr'])
Iterable object stukeys gets automatically updated.
keys()
>>> print(stukeys[2])
Triggers run-time error as discussed earlier.
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> stukeys=list(stu.keys())
>>> print(stukeys, stukeys[1])
Displays ['rn', 'na', 'th'] na
>>> stu['pr']=28
>>> print(stukeys)
Displays ['rn', 'na', 'th'], stukeys does not get updated
Returns values stored in a dictionary as an iterable object
>>> stu={'rn':24, 'na':'TARUN', 'th':47.5}
>>> stuvalues=stu.values()
>>> print(stu.values())
Displays dict_values([24, 'TARUN', 47.5])
>>> stu['pr']=28
>>> print(stuvalues)
Displays dict_keys([24, 'TARUN', 47.5, 28])
Iterable object stuvalues gets automatically updated.
values()
>>> print(stuvalues[2])
Triggers run-time error as discussed earlier.
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> stuvalues=list(stu.values())
>>> print(stuvalues, stuvalues[1])
Displays [24, 'TARUN', 47.5] TARUN
>>> stu['pr']=28
>>> print(stuvalues)
Displays [24, 'TARUN', 47.5], stuvalues does not get updated
Deletes a key from a dictionary and returns its value
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28, 'tt':75}
>>> print(stu.pop('tt'))
Displays 75, value for the key 'tt' and the key 'tt' is deleted from the dictionary
stu
pop() >>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu.pop('gr'))
Triggers run-time error since key 'gr' is not present in the dictionary stu
>>> print(stu.pop())
Triggers run-time error since pop() method needs one parameter

FAIPS, DPS Kuwait Page 6 of 9 © Bikram Ally


Python Notes Class XI Dictionary
Deletes last key from a dictionary and returns its value
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu.popitem())
Displays ('pr', 28), value for the last key pair and the key 'pr' is deleted from
popitem() the dictionary stu
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47}
>>> print(stu.popitem('th'))
Triggers run-time error since popitem()method does not have any parameter
Returns a list containing every key:value pair value as an iterable object
>>> stu={'rn':24, 'na':'RAJ'}
>>> stuitems=stu.items()
>>> print(stuitems)
Displays dict_items([('rn', 24), ('na', 'RAJ')])
items()
key:value pairs are as tuples in a list in an iterable.
>>> stu['th']=47
>>> print(stuitems)
Displays dict_items([('rn', 24), ('na', 'RAJ'), ('th', 47])
Iterable object stuitems gets automatically updated.
Creates a new dictionary from an iterable
>>> stu=dict.fromkeys(['rn', 'na', 'th'])
>>> print(stu)
Displays {'rn': None, 'na': None, 'th': None}
By default every key has value None.
>>> stu=dict.fromkeys(['rn', 'na', 'th'], '**')
>>> print(stu)
Displays {'rn': '**', 'na': '**', 'th': '**'}
Every key has value '**'.
Method fromkeys() with two parameters: first parameter (parameter from left) is
an iterable and second parameter (parameter from right) is a single value for every
fromkeys() key. If second parameter is missing, default value for every key is None.
>>> stu=dict.fromkeys(('rn', 'na', 'th'))
>>> print(stu)
Displays {'rn': None, 'na': None, 'th': None}
>>> stu=dict.fromkeys(('rn', 'na', 'th'), 'XX')
>>> print(stu)
Displays {'rn': 'XX', 'na': 'XX', 'th': 'XX'}
>>> stu=dict.fromkeys('ABC')
>>> print(stu)
Displays {'A': None, 'B': None, 'C': None}
>>> stu=dict.fromkeys('ABC', 10)
>>> print(stu)
Displays {'A': 10, 'B': 10, 'B': 10}
Returns the value of the key present in the dictionary (similar to get()method).
If the key does not exist, new key:value is appended to the dictionary (similar to
update() method)
>>> stu={'rn':24, 'na':'RAJ', 'th':47, 'pr':28}
setdefault() >>> print(stu.setdefault('na')) #same as stu.get('na')
Displays TARUN since value for the key 'na' is TARUN
>>> print(stu.setdefault('na', 'DEV'))
Displays TARUN since value for the key 'na' is RAJ and the default value (second
parameter) is ignored.
FAIPS, DPS Kuwait Page 7 of 9 © Bikram Ally
Python Notes Class XI Dictionary
>>> print(stu.setdefault('tt'))
Displays None since the key 'tt' is not present in the dictionary stu and new
key:value pair 'tt':None is appended to the dictionary stu.
>>> print(stu)
Displays {'rn':24, 'na':'RAJ', 'th':47, 'pr':28, 'tt':None}
>>> stu.popitem()
Deletes key 'tt' and its value.
>>> print(stu)
Displays {'rn':24, 'na':'RAJ', 'th':47, 'pr':28}
>>> print(stu.setdefault('tt':75))
Displays 75 since the key 'tt' is not present in the dictionary stu and new key:value
pair 'tt':75 is appended to stu, same as update({'tt':75}) method.
>>> print(stu)
Displays {'rn':24, 'na':'RAJ', 'th':47, 'pr':28, 'tt':75}
update() Appends key(s) to a dictionary
Discussed in details earlier

1. Create a Python dictionary student with the following keys:


roll integer (student roll number)
name string (student name)
marks a list of floating-point values with 5 elements (marks of 5 subjects)
Append following keys in the dictionary student:
total floating point (total of 5 subjects marks)
agg floating point (aggregate percentage = total/5)
Input values for key roll, name and marks. Calculate value for keys total and agg. Display student
dictionary on the screen.
ro=int(input('Roll? '))
na=input('Name? ')
ma,tm=[], 0
for k in range(5):
t=float(input('Marks? '))
ma+=[t]
tm+=t
student={'roll':ro, 'name':na, 'marks':ma}
student['total']=tm
student['agg']=tm/5
print(student)
OR,
student = { 'roll':int(input('Roll? ')),
'name':input('Name? '),
'marks':[int(input('Marks? ')) for k in range(5)] }
student['total']=sum(student['marks'])
student['agg']=student['total']/5
print(student)

2. Write a Python script to create dictionary employee with following keys:


code integer (employee code)
name string (employee name)
bsal floating point (basic salary)
Edit the dictionary employee by adding following keys:
hra floating point (house rent = 25% of basic salary)
da floating point (dearness allowance = 85% of basic salary)
gsal floating point (gross salary = basic salary + house rent + dearness allowance)
FAIPS, DPS Kuwait Page 8 of 9 © Bikram Ally
Python Notes Class XI Dictionary
itax income tax and it is calculated as:
Gross Salary Income Tax
<=200000 0% of Gross Salary
>200000 and <=500000 5% of Gross Salary
>500000 and <=1000000 7% of Gross Salary
>1000000 10% of Gross Salary
Input value for keys code, name and bsal. Calculate value for keys hra, da, gsal and itax. Display
dictionary employee on the screen.
employee={ 'code':int(input('Code? ')),
'name':input('Name? '),
'bsal': float(input('BSal? ')) }
employee['hra']=0.25*employee['bsal']
employee['da']= 0.85*employee['bsal']
employee['gsal']=employee['bsal']+employee['hra']+employee['da']
gsal=employee['gsal']
if gsal<=200000: bo=0.0
elif gsal<=500000: bo=0.05*gsal
elif gsal<=1000000: bo=0.07*gsal
else: bo=0.10*gsal
employee['itax']=itax
for key in employee: print(key, employee[key])
#for key in employee.keys(): print(key, employee[key])
#for key, value in employee.items(): print(key, value)

FAIPS, DPS Kuwait Page 9 of 9 © Bikram Ally

You might also like