Computer Science
CLASS-XII (Code No. 083)
DPS RKP Computer Science Department
Revision of the basics of Python covered in Class XI
PART-3
2021-2022
Unit 1: Computational Thinking and Programming - 2
Revision of the basics of Python covered in Class XI. REVIEW PART-3
● Lists: Definition, Creation of a list, Traversal of a list. Operations on a list
-concatenation, repetition, membership; functions/methods–len(), list(),
DPS RKP Computer Science Department
append(), extend(), insert(), count(), index(), remove(), pop(), reverse(),
sort(),min(), max(), sum(); Lists Slicing; Nested lists; finding the maximum,
minimum, mean of numeric values stored in a list; linear search on list of
numbers and counting the frequency of elements in a list.
2
List
List: It is mutable data type in Python. The content of List can be enclosed
inside a pair of square braces [].
DPS RKP Computer Science Department
Examples of List Contents:
# List containing same type of data
A=[45,67,89] # All integers
B=[67.5,92.5,87.5,45.0] # All real numbers
C=['RED','YELLOW','GREEN']# All strings
# List containing different types of data
D=[12,"AMAR",3400.50] # int,string and float
3
Assignment and Traversal
# List containing same type of data
A=[45,67,89,35,12]
print(A[0],A[3])
DPS RKP Computer Science Department
print(A[len(A)-1])
print(A[0]+A[1],A[2]+A[3])
for I in A: 45 35
print(I,end="-") 12
print() 112 124
for C in range(len(A)): 45-67-89-35-12-
print(A[C],end="#") 45#67#89#35#12#
4
Concatenation
A=[23,45] + Operator can be used to
B=[50,60,70] concatenate the two lists
C=A+B
DPS RKP Computer Science Department
-,*.//,%,** are not supported to
print(C) perform operations on two lists
D=B+A
print(D)
[23, 45, 50, 60, 70]
[50, 60, 70, 23, 45]
5
Concatenation
NML=['ANU','JAI'] + Operator can be used to
N=NML+['LEI'] concatenate the two lists
print(N)
DPS RKP Computer Science Department
-,*.//,%,** are not supported to
M=['KEN']+N perform operations on two lists
print(M)
L=['TAN']+NML+['JEN']
print(L)
['ANU', 'JAI', 'LEI']
['KEN', 'ANU', 'JAI', 'LEI']
['TAN', 'ANU', 'JAI', 'JEN']
6
Repetition
COL=['RED','BLUE'] * Operator can be used for repetition
of the content of the list
print(COL*2)
NUM=[1,2,3] or
DPS RKP Computer Science Department
List*int int*List
print(3*NUM)
Will produce the same result
['RED', 'BLUE', 'RED', 'BLUE']
[1, 2, 3, 1, 2, 3, 1, 2, 3]
7
Concatenation
L=[]
for I in range(4):
To add new content (concatenation)
L+=[int(input(">>"))]
DPS RKP Computer Science Department
in a list, it is a must to enclose it in a
print(L) pair of square braces.
>>23
>>45
>>56
>>87
[23, 45, 56, 87]
8
Concatenation
L=[]
for I in range(4):
To add new content (concatenation)
S=input("Name:")
DPS RKP Computer Science Department
in a list, it is must to enclose it in a
L+=[S] pair of square braces.
print(L)
Name:AMAR
Name:AKBAR
Name:ANTHONY
Name:ROMA
['AMAR', 'AKBAR', 'ANTHONY', 'ROMA']
9
List Mutability
A=[23,45,67,78] Note: We can change the
print(A) content of an individual
A[0]=38;A[2]=65 element of the list.
DPS RKP Computer Science Department
print(A)
for C in A:
C=C+2
print(C,end="*")
print()
print(A) [23, 45, 67, 78]
[38, 45, 65, 78]
40*47*67*80*
[38, 45, 65, 78]
10
List Mutability
Note: We can change the
A=[23,45,67,78]
content of an individual
print(A)
element of the list.
A[0]=38;A[2]=65
DPS RKP Computer Science Department
print(A)
for i in range(len(A)):
A[i]+=2
print(A[i],end="*")
print()
print(A) [23, 45, 67, 78]
[38, 45, 65, 78]
40*47*67*80*
[40, 47, 67, 80]
11
List Membership
Stock=['A',25,32,'C'] Note: ‘in’ is a membership
Item =['A','B'] operator, it checks if the
Values=[25,32,61] required content is present in
the list or not
DPS RKP Computer Science Department
for S in Stock:
if S in Item:
print(S,"is in Item")
if S in Values:
print(S,"is in Values")
else: A is in Item
print(S,"is not in Values") A is not in Values
25 is in Values
32 is in Values
C is not in Values
12
List - Functions len(), list(), append()
A=(25,56,34) len() - finds the number of values in list
print(A,len(A)) list() - converts a collection to list
A=list(A) append() - adds a single value to list
DPS RKP Computer Science Department
print(A,len(A))
A.append(25)
print(A,len(A))
A.append('END')
print(A,len(A))
(25, 56, 34) 3
[25, 56, 34] 3
[25, 56, 34, 25] 4
[25, 56, 34, 25, 'END'] 5
13
List - Functions len(), list(), append()
A=[25,56,34] append() - adds a list also as a single value
print(A,len(A)) to another list
B=[45,29]
DPS RKP Computer Science Department
print(A,len(A))
A.append(B)
print(A,len(A))
print(B,len(B))
[25, 56, 34] 3
for I in A:
[25, 56, 34] 3
if type(I)==list:
[25, 56, 34, [45, 29]] 4
print(I)
[45, 29] 2
else:
25*56*34*[45, 29]
print(I,end="*")
NOTE: type() - returns the data type of the content
14
List - Functions type()
A=[34,"AM",[1,"PM"],['A','B','C'],4.3]
for I in A:
if type(I)==list: type() - returns the type of the data
print(I,end="*")
DPS RKP Computer Science Department
elif type(I)==int:
print(I,end="@")
elif type(I)==float: ] *4.3#
print(I,end="#") ' , 'C'
B
[ ' A', '
elif type(I)==str:
' P M']*
print(I,end="&") A M & [1,
34@
else:
print(end=="$")
15
List - Functions append() and extend()
append() adds its argument/parameter as a single element to the end of a list.
The length of the list itself will increase by one.
extend() iterates over its argument/parameter by adding each element to the
DPS RKP Computer Science Department
list, extending the list. The length of the list will increase by as many elements
that were present in the iterable argument/parameter.
A=[] A=[]
A.append(32) # Correct A.append([32,45]) # Correct
A.extend(32) # TypeError A.extend([32,45]) # Correct
In the above example on the right side append() will add a single value
whereas extend() will extend the list by two elements
16
List - Functions len(), list(), extend()
A=[25,56,34] extend() - iterates over its
print(A,len(A)) argument/parameter by adding each
B=[45,29] element to the list
DPS RKP Computer Science Department
print(B,len(B))
A.extend(B)
print(A,len(A)) In this example if won't return True
for I in A:
if type(I)==list:
print(I) [25, 56, 34] 3
else: [45, 29] 2
print(I,end="*") [25, 56, 34, 45, 29] 5
25*56*34*45*29*
17
List - Function insert()
A=[25,56,34] insert() - inserts the value (second parameter)
A.insert(1,45) at the index (first parameter)
print(A,len(A))
DPS RKP Computer Science Department
A.insert(0,12)
The value is inserted at the end of the list if
print(A,len(A)) the index is much beyond the given length
A.insert(100,76) of the list
print(A,len(A))
[25, 45, 56, 34] 4
[12, 25, 45, 56, 34] 5
[12, 25, 45, 56, 34, 76] 6
18
List - Function insert()
A=[25,56,34] insert() - inserts the value (second
A.insert(1,[39,91]) parameter) at an index (first parameter)
print(A,len(A))
DPS RKP Computer Science Department
A.insert(0,[12,65])
print(A,len(A))
A.insert(100,[76])
print(A,len(A))
[25, [39, 91], 56, 34] 4
[[12, 65], 25, [39, 91], 56, 34] 5
[[12, 65], 25, [39, 91], 56, 34, [76]] 6
19
List - Function count()
A=[23,56,89,56] count() - counts the value passed as a
print(A.count(56)) parameter from the list
print(A.count(23))
DPS RKP Computer Science Department
print(A.count(65)) If the value doesn’t exist, then the
function returns 0
print(A.count('A'))
2
1
0
0
20
List - Function index()
A=[23,56,89,56] index() - returns the index of the value
passed as a parameter from the list
print(A.index(23))
Raises ValueError exception if the value
print(A.index(89)) not found in the list
DPS RKP Computer Science Department
print(A.index(56))
print(A.index(34))
0
2
1
---------
ValueError
21
Quick Review - insert(), append(), extend()
append() extend() insert()
A function/method A function/method A function/method
DPS RKP Computer Science Department
Adds a single Extends the list Inserts a new value
element (a with new values at a specified
value/list) at the from another list index. Inserts at
end at the end of at the end of the the end if the
the list list index specified is
out of range.
22
List - Function remove() and pop()
remove() - deletes the value passed as
A=[23,56,89,56,76]
parameter. Raises ValueError if the value
A.remove(23)
not found
print(A)
pop() - deletes the value as per the index
DPS RKP Computer Science Department
D=A.pop()
passed as a parameter and also returns the
print(A,D,"gone")
deleted value. Raises IndexError if the
E=A.pop(1)
index out of range of list
print(A,E,"gone")
F=A.pop(4) [56, 89, 56, 76]
print(A,F,"gone") [56, 89, 56] 76 gone
[56, 56] 89 gone
A.remove(203) --------
# will raise ValueError IndexError
23
List - del
A=[34,56,78,32,62,91]
del A[3],A[0] del - it is a keyword used to delete an element
print(A) or multiple elements from a list. Raises
DPS RKP Computer Science Department
IndexError if the index out of range of list
del A[0]
print(A)
del A[5]
[56, 78, 62, 91]
print(A) [78, 62, 91]
----------
IndexError
24
Quick Review - remove(), pop(), del
remove() pop() del
A function/method A function/method A keyword
DPS RKP Computer Science Department
deletes the value passed deletes the value as per deletes an element or
as parameter. the index passed as a multiple elements from
parameter and also a list.
Raises ValueError if returns the deleted
the value not found value. Raises IndexError if
Raises IndexError if the index out of range
the index out of range of list
of list
25
List - reverse()
A=[23,76,54,34] reverse - a method to reverse the content
A.reverse() of a list irrespective of the data types of
print(A) values it contains
DPS RKP Computer Science Department
B=["A","B","C","D"]
B.reverse()
print(B)
C=["A",100,"B",200]
C.reverse() [34, 54, 76, 23]
print(C) ['D', 'C', 'B', 'A']
[200, 'B', 100, 'A']
26
List - min(),max(),sum() and sort()
A=[23,98,45,34,67] min(),max() - methods return the minimum
and the maximum values in the list
print(A) sum() - method returns the sum of values in the
print("Low:",min(A)) list. Supports only numeric values, raises
DPS RKP Computer Science Department
print("High:",max(A)) TypeError if used with non-numeric values
sort() - arranges the homogeneous content in
print("Total:",sum(A))
order (ascending by default)
A.sort()
for I in A: [23, 98, 45, 34, 67]
print(I,end="#") Low: 23
High: 98
Total: 267
23#34#45#67#98#
27
List - min(),max(),sum() and sort()
A=["A","Z","CA","M"] min(),max() - methods return the minimum
and the maximum values from the list
print(A) sum() - method returns the sum of values in the
print("Low:",min(A)) list. Supports only numeric values, raises
DPS RKP Computer Science Department
print("High:",max(A)) TypeError if used with non-numeric values
sort() - arranges the homogeneous content in
A.sort() order (ascending by default)
for I in A:
print(I,end="#") ['A', 'Z', 'CA', 'M']
Low: A
print("Total:",sum(A))
High: Z
A#CA#M#Z#
-------
TypeError
28
List - min(),max(),sum() and sort()
A=["Anu","Zen","Jak","Bob"]
print(A)
print("Low:",min(A))
DPS RKP Computer Science Department
sort() - To sort in reverse order, we use
print("High:",max(A))
reverse=True
A.sort(reverse=True) as parameter with sort function
for I in A:
print(I,end="*") ['Anu', 'Zen', 'Jak', 'Bob']
print("\n",A) Low: Anu
High: Zen
Zen*Jak*Bob*Anu*
['Zen', 'Jak', 'Bob', 'Anu']
29
List - min(),max(),sum() and sort()
A=["A",25,"CA",56]
print(A)
print("Low:",min(A)) min(),max(),sort() -
DPS RKP Computer Science Department
print("High:",max(A)) methods require homogeneous
collection as content of list
A.sort()
Will raise TypeError for mixed
for I in A: data types
print(I,end="#")
print("Total:",sum(A)) ['A', 25', 'CA', 56]
-------
TypeError
30
Logic for finding min and max values
A=[25,67,43,56,12] A=[25,67,43,56,12]
MIN=A[0] MIN=0
MAX=A[0] MAX=0
DPS RKP Computer Science Department
L=len(A) L=len(A)
for I in range(1,L):
for I in range(1,L):
if MIN>A[I]:
MIN=A[I] if A[MIN]>A[I]:
if MAX<A[I]: MIN=I
MAX=A[I] if A[MAX]<A[I]:
print("MIN:",MIN,"MAX:",MAX) MAX=I
print("MIN:",A[MIN],"MAX:",A[MAX])
MIN: 12 MAX: 67
31
List - slicing
A=[23,43,56,89,65,32]
[23, 43, 56, 89]
print(A[0:4])
[23, 43, 56, 89, 65, 32]
print(A[:6])
DPS RKP Computer Science Department
[89, 65, 32]
print(A[3:])
[23, 56, 65]
print(A[::2])
[32, 65, 89, 56, 43, 23]
print(A[::-1])
[32, 89, 43]
print(A[::-2])
[23, 43, 56, 89, 65, 32]
print(A[::])
[]
print(A[4:1])
[89, 65, 32]
print(A[3::]
32
Logic for finding a Value from a List
A=[56,23,12,78,98,43]
D=int(input("Data:")) Data:65
if D in A: Value: 65 Not Found
print("Value:",D,"Found!") 65 Not Found
DPS RKP Computer Science Department
else:
print("Value:",D,"Not Found") Python way of searching
for I in A:
if I==D:
print(D,"Found") Traditional logic of Linear Search
break
else: Data:23
print(D,"Not Found") Value: 23 Found!
23 Found
33
List -Nested lists
A=[34,56,[1,2],['A','B','C'],43]
for I in A: 34
print(I) 56
DPS RKP Computer Science Department
for I in A: [1, 2]
['A', 'B', 'C']
if type(I)!=list:
43
print(I,end="*") 34*56*[1, 2]
else: ['A', 'B', 'C']
print(I) 43*['A', 'B', 'C']
# printing content of index 3
print(A[3])
34
List -Nested lists
A=[[1,2,3],[3,4,5],[5,6,7]]
for I in A:
print(I) [1, 2, 3]
DPS RKP Computer Science Department
for I in A: [3, 4, 5]
for J in I: [5, 6, 7]
1-2-3-
print(J,end="-")
3-4-5-
print() 5-6-7-
for i in range(len(A)): [1]
print(A[i][0:i+1]) [3, 4]
[5, 6, 7]
35
List -Nested lists
A=[[1,2,3],[3,4,5],[5,6,7]]
for I in A:
print(I)
DPS RKP Computer Science Department
Inner LIST is also a mutable data
for i in range(len(A)): type. At any element change will
A[i][0]+=5 be reflected in the result
print(A)
for I in A: [1, 2, 3]
I[0]+=5;I[2]+=10 [3, 4, 5]
print(A) [5, 6, 7]
[[6, 2, 3], [8, 4, 5], [10, 6, 7]]
[[11, 2, 13], [13, 4, 15], [15, 6, 17]]
36
List -Nested lists
L=[0,1,2,3,4]
for i in L:
i+=10 # int, float, str - immutable
print(i,end="* ")
DPS RKP Computer Science Department
print(i," List ",L)
L=[[1,2,3],[3,4,5]]
for i in L:
i[0]+=10 # list - mutable i[0] <----> L[0][0]
print(i," List ",print(L)
10* 11* 12* 13* 14* 14 List [0, 1, 2, 3, 4]
[13, 4, 5] List [[11, 2, 3], [13, 4, 5]]
37
List -Nested lists
A=[[7,3],[2,1,4],[4,1,5],[8,4,6,1],[1,9]]
A.sort() #Sorting on First value of each
print(A)
DPS RKP Computer Science Department
A[2].sort() #Sorting content of A[2] in the nested list
print(A[2])
print(A)
[[1, 9], [2, 1, 4], [4, 1, 5], [7, 3], [8, 4, 6, 1]]
[1, 4, 5]
[[1, 9], [2, 1, 4], [1, 4, 5], [7, 3], [8, 4, 6, 1]]
38
List - To find frequency of values in a List
A=[1,2,1,4,3,2,4,5,1]
MIN=min(A) 1 Frequency 3
MAX=max(A) 2 Frequency 2
AVG=sum(A)/len(A)
DPS RKP Computer Science Department
3 Frequency 1
for i in range(MIN,MAX+1): 4 Frequency 2
print(i,"Frequency",A.count(i)) 5 Frequency 1
for i in range(MIN,MAX+1): 1 ###
print(i,"#"*A.count(i)) 2 ##
print("Mean:",round(AVG,2)) 3 #
4 ##
5 #
Mean: 2.56
39
List - To swap the first half of list with second
A=[11,22,33,44,55,66]
0 1 2 3 4 5
L=len(A)
for i in range(L//2): 11 22 33 44 55 66
DPS RKP Computer Science Department
A[i],A[L//2+i]=A[L//2+i],A[i]
print(A)
for i in range(L):
if i==L//2:
print()
print(A[i],end='-') [44, 55, 66, 11, 22, 33]
44-55-66-
11-22-33-
40
List - To swap the first half of list with second
A=[11,22,33,44,55,66]
L=len(A) Python Way
A[:L//2],A[L//2:]=A[L//2:],A[:L//2]
DPS RKP Computer Science Department
print(A)
for i in range(L):
if i==L//2:
print()
print(A[i],end='-')
[44, 55, 66, 11, 22, 33]
44-55-66-
11-22-33-
41
List - To swap the the alternate values
A=[11,22,33,44,55,66]
0 1 2 3 4 5
L=len(A)
print(A) 11 22 33 44 55 66
DPS RKP Computer Science Department
for i in range(0,L,2):
A[i],A[i+1]=A[i+1],A[i]
print(A)
for i in range(0,L,2):
[11, 22, 33, 44, 55, 66]
print(A[i],A[i+1],sep="#")
[22, 11, 44, 33, 66, 55]
22#11
44#33
66#55
42
List - To accumulate sum of previous values
A=[11,22,33,44,55,66]
L=len(A)
print(A)
DPS RKP Computer Science Department
for i in range(1,L):
A[i]+=A[i-1] [11, 22, 33, 44, 55, 66]
print(A) [11, 33, 66, 110, 165, 231]
for i in range(L): #11
#33
print(" "*i,A[i],sep="#")
#66
#110
#165
#231
43
List - To find min of 1st half and max of 2nd
A=[1,4,8,3,7,2,5,9,0,5]
L=len(A)
DPS RKP Computer Science Department
print("Min of",A[:L//2],"is",min(A[:L//2]))
print("Max of",A[L//2:],"is",max(A[L//2:]))
Min of [1, 4, 8, 3, 7] is 1
Max of [2, 5, 9, 0, 5] is 9
44
List - To find sum of 1st half and avg of 2nd
A=[1,4,8,3,7,2,5,9,0,5]
L=len(A)
DPS RKP Computer Science Department
H=len(A[L//2:])
print("Sum of",A[0:L//2],"is",sum(A[0:L//2]))
print("Avg of",A[L//2:],"is",sum(A[L//2:])/H)
Sum of [1, 4, 8, 3, 7] is 23
Avg of [2, 5, 9, 0, 5] is 4.2
45
Happy Learning…
DPS RKP Computer Science Department
Thank you!
Department of Computer Science
46