UNIT-IV
LISTS, TUPLES, DICTIONARIES
Lists
• A list is a sequence of values of any type, placed
within square brackets and with comma
separator. [item1, item2,.....,item n]
• The values in a list are called elements or
sometimes items.
• Insertion order preserved.
• Duplicate objects are allowed.
• Heterogeneous objects are allowed.
• List is dynamic because based on our
requirement we can increase the size and
decrease the size.
i=[10,20,’a’,’b’,45,’f’]
List representation:
-ve index
+ve index
-6 -5 -4 -3 -2 -1
10 20 a b 45 f
0 1 2 3 4 5
Contd., Output
>>>l=[]
>>> print(l)
>>> print(type(l))
>>>l=[10,20,30,'a','b',40,10,20]
>>> print(l)
>>> print(type(l))
Empty List
[]
<class 'list'>
Enter list:
[10,20,30,'a','b',40,10,20]
[10, 20, 30, 'a', 'b', 40, 10,20]
<class 'list'>
Contd.,
range(start, stop, step)
>>> l=list(range(0,10,2))
>>> print(l)
String List()
>>>Mylist=[“one”,“two”,“three”]
for items in Mylist:
print(items)
>>> s='Learning python is very
easy !!!'
>>> l=s.split()
>>> print(l)
Output:
[0, 2, 4, 6, 8]
one
two
three
['Learning', 'python',
'is', 'very', 'easy', '!!!']
List within another List
• Eg:
>>> a=5
>>> b=‘xyz’
>>> c=[a, b]
>>> seq=[a, b, c]
>>>seq
[5, ‘xyz’, [5, ‘xyz’]]
>>> l=list([10,20,30,[40,50]])
>>> print(l)
[10, 20, 30, [40, 50]]
Contd.,
Using for loop
range()
x=[10,20,'a','b',45,'f']
>>> for i in range(len(x)):
print(x[i])
10
20
a
b
45
F
Accessing Elements of List:
• We can access elements of the list either by using
index or by using slice operator(:)
1) By using Index:
• List follows zero based indexes. ie index of first
element is zero.
• List supports both +ve and -ve indexes.
• i=[10,20,’a’,’b’,45,’f’] >>> print(l[0])
10
• >>> print(l[-2])
• 30 45
Contd.,
• By using Slice Operator:
Syntax: list2 = list1[start:stop:step]
• Start It indicates the Index where slice has to
start
Default Value is 0
• Stop It indicates the Index where slice has to
End
Default Value is max allowed Index of List
ie Length of the List
• Step  increment value
Default Value is 1
Contd.,
>>> i=[10,20,'a','b',45,'f']
>>>print( i[:5])
>>> print(i[:])
>>>print(i[3:4])
>>>print( i[5:100])
>>> print(i[100])
[10, 20, 'a', 'b', 45]
[10, 20, 'a', 'b', 45, 'f']
['b']
['f']
Traceback (most recent call last):
File "<pyshell#62>", line 1, in
<module>
i[100]
IndexError: list index out of range
List Index
• Index operator  [ ]
• Index starts with 0.
• Index must be an integer.
• Nested lists are accessed using Nested Indexing.
• Eg:
>>>mylist=[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
>>>print(mylist[0])  prints ‘p’
>>>print(mylist[2])  prints t
>>>print(mylist[-2])  prints ‘o’
# Nested Lists Example
>>>N_list=[“Happy”, [2, 0, 1, 7]]
>>>print(N_list)
>>>print(N_list[0][1])  prints ‘a’
>>>print(N_list[1][2])  prints 1
Contd.,
Lists are mutable: Changeable
>>>i=[10,20,'a','b',45,'f']
>>>print(i[4])
45
>>> i[4]='U'
>>> print(i)
[10, 20, 'a', 'b', 'U', 'f']
Contd.,
>>>i=[10, 20, 'a', 'b', 'U', 'f']
>>>r=[1,2,3,4,5]
>>> l=['q','w','e','r','t','y']
>>> print(i,r,l)
[10, 20, 'a', 'b', 'U', 'f'] [1, 2, 3, 4, 5] ['q', 'w', 'e', 'r', 't', 'y']
>>> 'q'in l
True
>>> 'q' in r
False
Basic List Operations
Expression Results Description
len([1, 2, 3, 4]) 4 Length of the list
[1,2,3,4]+[5,6,7,8] [1,2,3,4,5,6,7,8] Concatenation
[“Hi!”] * 2
[1,2,3]*2
[“Hi!”, “Hi!”]
[1,2,3,1,2,3]
Repetition
2 in [1, 2, 3, 4, 5] True Membership
for x in [1, 2, 3, 4, 5]:
print(x, end=“ ”)
1 2 3 4 5 Iteration
List Methods
Methods Description
append() Add an element to the list
extend() Add several elements to a list at a time
insert() Insert an item at the specified index
remove() Removes the specified item from the list
pop() Removes and returns the element at the given index
clear() Removes all elements from the list
index() Returns the index position of the first matched item
count()
Returns the count of number of items passed as an
argument
sort() Sort items in a list in ascending order
reverse() Reverses the order of the list
copy() Copies the list to another list
append() method
• Lists are mutable. i.e. elements can be added or removed as
and when needed.
• Eg:
List=[123, “Python”, “Language”]
print(“Original List is: ”, List)
List.append(“2019 Batch”)
print(“Updated List is: ”, List)
Output:
Original List is: [123, “Python”, “Language”]
Updated List is: [123, “Python”, “Language”,
“2019 Batch”]
Contd.,
l=[]
for i in range (101):
if(i%10)==0:
l.append(i)
print(l)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Deleting the elements
• Two ways:
1. del statement if exact element location is known.
2. remove() method if the exact locations are not
known.
Eg:
List=[123, “Python”, “Language”]
print(List)
del List[0]
print(List) OUTPUT:
[123, “Python”, “Language”]
[“Python”, “Language”]
remove() method
• Eg:
List=[10, 20, 30, 20, 50, 20]
print(List)
List.remove(20)
print(List)
Note that only the first instance of 20 alone was removed.
OUTPUT:
[10, 20, 30, 20, 50, 20]
[10, 30, 20, 50, 20]
Insert()
 The elements are
inserted at a specified
position.
>>> l=[1,2,3,5,6,7]
>>> l.insert(3,4)
>>> print(l)
>>> print(l)
>>> l.insert(10,9)
>>> print(l)
>>> l.insert(-10,8)
>>> print(l)
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 9]
[8, 1, 2, 3, 4, 5, 6, 7, 9]
Extend()
Add all item of one list to
another list
>>> l=['hai','hello']
>>> m=['good','morning']
>>> l.extend(m)
>>> print(l)
>>> m.extend(l)
>>> print(m)
['hai', 'hello', 'good', 'morning']
['good', 'morning', 'hai', 'hello']
append() and extend()
• append()  used to add one element at a time to list.
• extend()  used to add several elements at a time to
list.
• Eg:
>>>even=[2, 4, 6]
>>>print(even)  prints 2 4 6
>>>even.append(8)
>>> print(even)  prints 2 4 6 8
>>>even.extend([10, 12, 14])
>>>print(even)  prints 2 4 6 8 10 12 14
Pop()
It removes last element of the list
This function has return value
l=[1,2,3,4,5,6,7,8,9]
>>> x=l.pop()
>>> print(x) 9
>>> print(l) [1, 2, 3, 4, 5,6, 7, 8]
>>> n=[]
>>> x=n.pop() Traceback (most recent call last):
File "<pyshell#70>", line 1, in
<module> x=n.pop()
IndexError: pop from empty list
Advanced List Processing
MAP, REDUCE AND FILTER(list comprehension)
• MapA Processing pattern that traverses a sequence
and performs an operation on each element.
• Reduce A Processing pattern that traverses a
sequence and accumulates the elements into a
single result.
• Filter A Processing pattern that traverses a
sequence and select the elements that satisfy some
criterion.
Map and reduce
t=[9,8,7,6,5,4]
tot=0
for i in t:
tot=tot+i
print(tot) 39
print(sum(t)) 39
(reduce : sequence of steps into one statement)
filter
>>> t=['a','A','b','B','C','c']
>>>l=[]
>>> for s in t:
if s.islower():
l.append(s)
>> print(l)
['a', 'b', 'c']
List Comprehension
>>> l=[x*x for x in range(11)]
>>> print(l)
>>> l=[x*x for x in range(1,11)]
>>> print(l)
>>> l=[x*x for x in range(1,11,2)]
>>> print(l)
>>> l=[x*x for x in range(0,11,2)]
>>> print(l)
[0, 1, 4, 9, 16, 25, 36, 49,
64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64,
81, 100]
[1, 9, 25, 49, 81]
[0, 4, 16, 36, 64, 100]
Create a list of objects from any inerrable objects.
Syntax: VN=[expression for item in list if condition]
Contd.,
l=[2**x for x in range(1,6)]
>>> print(l) [2, 4, 8, 16, 32]
>>> s=[1,4,9,16,25,36,49,64,81,100]
>>> l=[x for x in s if(x%2==0)]
>>> print(l) [4, 16, 36, 64, 100]
words=['hai','hello','good','morning']
>>> l=[w[0] for w in words]
>>> print(l) ['h', 'h', 'g', 'm‘]
List as parameters
• In python, arguments are passed by reference.
• If any changes are done in the parameter which
refers within the function, then the changes also
reflects back in the calling function.
• When a list to a function is passed, the function gets
a reference to the list, access to the original list, but
does not create a new copy of list.
List as parameters
def remove(a):
a.remove(1)
print(a)
a=[1,2,3,4,5]
remove(a)
[2,3,4,5]
def insert(a):
a. insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
[30,2,3,4,5]
Aliasing and Cloning
Cloning:
• Cloning means making
an exact but separate
copy without modifying
the original list.
• creating a copy of a
same list of elements
with two different
memory locations is
called cloning.
• Changes in one list will
not affect locations of
another list.
Aliasing:
• Creating a copy of a list is
called aliasing.
• When you create a copy
both list will be having
same memory location.
• Changes in one list will
affect another list.
• Aliasing refers to having
different names for same
list values.
List Aliasing
>>>list1 = [10, 20, 30, 40]
>>>list2= list1
>>>list1[0] = 5
>>>list1
[5, 20, 30, 40] change made in list1
>>>list2
[5, 20, 30, 40] change in list1 causes a change in
list2
List cloning
>>>list1 = [10, 20, 30, 40]
>>>list2= list1[:]
>>>list2[0] = 5
>>>list1
[10, 20, 30, 40] change not made in list1
>>>list2
[5, 20, 30, 40] change made in list2
Sum of elements in list
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
Home practices – Slice Operator
>>> l=[1,2,3,'a','b',4,5]
>>> print(l[:])
>>> print(l[::])
>>> print(l[-1:-7])
>>> print(l[-1::-7])
>>> print(l[-1::])
>>> print(l[0::-1])
>>> print(l[::-1])
>>> print(l[::-7])
[1, 2, 3, 'a', 'b', 4, 5]
[1, 2, 3, 'a', 'b', 4, 5]
[]
[5]
[5]
[1]
[5, 4, 'b', 'a', 3, 2, 1]
[5]
Tuples (values)
 Tuple assignment
 Tuple as return value
• Tuple is exactly same as List except that it is
immutable. i.e once we creates Tuple object, we
cannot perform any changes in that object.
• Hence Tuple is Read only version of List.
• If our data is fixed and never changes then we
should go for Tuple.
• Insertion Order is preserved
• Duplicates are allowed
• Heterogeneous objects are allowed.
• We can preserve insertion order and we can
differentiate duplicate objects by using index.
Hence index will play very important role in Tuple
also.
• Tuple support both +ve and -ve index. +ve index
means forward direction (from left to right) and -
ve index means backward direction (from right to
left)
• We can represent Tuple elements within
Parenthesis and with comma separator.
Home practices – Slice Operator -TUPLE
>>> a=(1,2,3,4)
>>> print(a[:])
>>> print(a[:-1])
>>> print(a[::-1])
>>> print(a[-4::])
>>> print(a[:0:])
>>> print(a[:2])
>>> print(a[2::])
>>> print(a[1:3])
>>> print(a[-4:-2])
>>> print(a[-2:])
>>> print(a[-3:-1])
(1, 2, 3, 4)
(1, 2, 3)
(4, 3, 2, 1)
(1, 2, 3, 4)
()
(1, 2)
(3, 4)
(2, 3)
(1, 2)
(3, 4)
(2, 3)
methods example description
list( ) a=(1,2,3,4,5) it convert the
a=list(a) given tuple into list.
print(a)
[1, 2, 3, 4, 5]
tuple( ) a=[1,2,3,4,5] it convert the given
a=tuple(a) list into tuple.
print(a) (1, 2, 3, 4, 5)
Benefit of Tuple:
• Tuples are faster than lists.
• If the user wants to protect the data from accidental
changes, tuple can be used.
• Tuples can be used as keys in dictionaries, while lists
can't.
Operations on Tuples:
• Indexing
• Slicing
• Concatenation
• Repetitions
• Membership
• Comparison
Operations Examples Description
Creating a tuple a=(20,40,60,”apple”,”ball”) Creating the tuple with elements of
different data types.
Indexing print(a[0]) 20
a[2] 60
Accessing the item in the position 0
Accessing the item in the position 2
Slicing print(a[1:3]) (40,60) Displaying items from 1st till 2nd.
Concatenation b=(2,4) >>>print(a+b)
(20,40,60,”apple”,”ball”,2,4)
Adding tuple elements at the end of
another tuple elements
Repetition print(b*2)
(2,4,2,4)
repeating the tuple in n no of times
Membership a=(2,3,4,5,6,7,8,9,10)
5 in a True
100 in a False
2 not in a False
Returns True if element is present in
tuple. Otherwise returns false.
Comparison a=(2,3,4,5,6,7,8,9,10)
b=(2,3,4)
a==b False
a!=b True
Returns True if all elements in both
elements are same. Otherwise returns
false
>>> t=10,20,30,40
>>> print(t) (10, 20, 30, 40)
>>> print(type(t)) <class 'tuple'>
>>> t=()
>>> print(t) ()
>>> print(type(t)) <class 'tuple'>
>>> t=(10)
>>> print(type(t)) <class 'int'>
>>> t=(10,)
>>> print(t) (10,)
>>> print(type(t)) <class 'tuple'>
Tuple Vs. Immutability
• As we can’t update the values of tuple it is
immutable.
>>> t=10,20,30,40
>>> t[1]=90
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
t[1]=90
TypeError: 'tuple' object does not support item
assignment
Mathematical Operators for tuple
We can apply + and * operators for tuple
Concatenation operator (+)
>>>t=10,20,30,40
>>> t1=50,60,70,80,90
>>> print(t+t1)
(10, 20, 30, 40, 50, 60, 70,
80, 90)
Multiplication / Repetition
Operator (**)
>>>print(t*2)
(10, 20, 30, 40, 10, 20, 30,
40)
Tuple Assignment
a,b=10, 20
>>> a,b=10,20
>>> print(a)
10
>>> print(b)
20
>>> a,b=b,a
>>> print(a)
20
>>> print(b)
10
Tuple as return value
• The function can only return one value, but if
the value is a tuple, the effect is the same as
returning multiple values.
• Divmod function takes two arguments input
and returns a tuple of two values.
a=divmod(45,5)
>>> print(a) (9, 0)
Tuple as Return Values
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=int(input("enter a value:"))
b=int(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Dictionary {key:value}
• We can use List, Tuple to represent a group of
individual objects as a single entity.
• If we want to represent a group of objects as key-
value pairs then we should go for Dictionary.
• Duplicate keys are not allowed but values can be
duplicated.
• Heterogeneous objects are allowed for both key
and values.
• Dictionaries are mutable
• Dictionaries are dynamic
• Indexing and slicing concepts are not applicable
Real Time Example
• Eg: Telephone Diary
• We may remember only the names of the
contacts and not their numbers.
• So storing it in a dictionary would be easier to
retrieve the value with given name key.
How to create dictionary?
>>> d={}
>>> print(d) {}
>>> print(type(d)) <class 'dict'>
>>> d=dict()
>>> print(d) {}
>>> print(type(d)) <class 'dict'>
>>> d[1]='Hello'
>>> d[2]='Hai'
>>> d[3]='Everyone'
>>> d[5]='Have Nice Day'
>>> print(d)
{1: 'Hello', 2: 'Hai', 3: 'Everyone', 5: 'Have Nice Day'}
How to access data from dictionary
We can access data by using keys
D={1: 'Hello', 2: 'Hai', 3: 'Everyone', 5: 'Have Nice Day'}
>>> print(d[3]) Everyone
>>> print(d[0]) Traceback (most recent call last):
File "<pyshell#51>", line 1, in
<module> print(d[0])
KeyError: 0
>>> print(d.keys()) dict_keys([1, 2, 3, 5])
>>> print(d.values())
dict_values(['Hello', 'Hai', 'Everyone', 'Have Nice Day'])
How to update Dictionaries?
• d[key]=value
• If the key is not available then a new entry will be
created with the specified key-value pair.
• If the key already available, then the old value will
be replaced with new value.
d={1: 'Hello', 2: 'Hai', 3: 'Everyone', 5: 'Have Nice Day'}
>>> d[3]='buddy'
>>> print(d)
{1: 'Hello', 2: 'Hai', 3: 'buddy', 5: 'Have Nice Day'}
>>> print(d)
{1: 'Hello', 2: 'Hai', 3: 'buddy', 5: 'Have Nice Day', 4: 24}
How to delete elements from dictionaries
del d[key] -> deletes an entry stored in a specified
key.
d={1: 'Hello', 2: 'Hai', 3: 'buddy', 5: 'Have Nice Day', 4:
24}
>>> del d[5]
>>> print(d) {1: 'Hello', 2: 'Hai', 3: 'buddy', 4: 24}
>>> del d[6] Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
del d[6]
KeyError: 6
d.clear() -> remove all entries from dictionaries
>>>d= {1: 'Hello', 2: 'Hai', 3: 'buddy', 4: 24}
>>> d.clear()
>>> print(d) {}
>>> d={1: 'Hello', 2: 'Hai', 3: 'buddy', 4: 24}
>>> del d
>>> print(d) Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
print(d)
NameError: name 'd' is not defined
Operations on dictionaries
Operations Example Description
Creating a
dictionary
>>> a={1:"one",2:"two"}
>>> print(a)
{1: 'one', 2: 'two'}
Creating the dictionary with
elements of different data types.
accessing an
element
>>> a[1]
'one'
>>> a[0] KeyError: 0
Accessing the elements by using
keys.
Update >>> a[1]="ONE"
>>> print(a)
{1: 'ONE', 2: 'two'}
Assigning a new value to key. It
replaces the old value by new
value.
add element >>> a[3]="three"
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three'}
Add new element in to the
Dictionary with key.
membership a={1: 'ONE', 2: 'two', 3: 'three'}
>>> 1 in a
True
>>> 3 not in a
False
Returns True if the key is present
in dictionary. Otherwise returns
false.
Methods in dictionaries
Method Example Description
a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'}
>>> b=a.copy()
>>> print(b)
{1: 'ONE', 2: 'two', 3: 'three'}
It returns copy of the dictionary. here
copy of dictionary ‟a‟ get stored in to
dictionary „b‟
a.items() >>> a.items()
dict_items([(1, 'ONE'), (2, 'two'),
(3,'three')])
Return a new view of the dictionary's
items. It displays a list of dictionary‟s
(key, value) tuple pairs.
a.keys() >>> a.keys()
dict_keys([1, 2, 3])
It displays list of keys in a dictionary
a.values() >>> a.values()
dict_values(['ONE', 'two', 'three'])
It displays list of values
in dictionary
a.pop(key) >>> a.pop(3)
'three'
>>> print(a)
{1: 'ONE', 2: 'two'}
Remove the element with key and
return its value from the dictionary.
a.update(dictionary) >>> b={4:"four"}
>>> a.update(b)
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three', 4:
'four'}
It will add the dictionary with
the existing dictionary
fromkeys() >>> key={"apple","ball"}
>>> value="for kids"
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
t creates a dictionary from key
and values
len(a) {'apple': 'for kids', 'ball': 'for kids'}
>>>lena(a)
3
It returns the length of the list.
clear() a={1: 'ONE', 2: 'two', 3: 'three'}
>>>a.clear()
>>>print(a)
>>>{ }
Remove all elements form the
dictionary.
del(a) a={1: 'ONE', 2: 'two', 3: 'three'}
>>> del(a)
It will delete the entire
dictionary.
List Tuple Dictionary
A list is mutable A tuple is immutable
Lists are dynamic Tuples are fixed size in
nature
List are enclosed in brackets[ ]
and their elements and size
can be changed
Tuples are enclosed in
parenthesis ( )
and cannot be updated
Tuples are enclosed in curly
braces
{ } and consist of key: value
Homogenous Heterogeneous Homogenous
Example:
List = [10, 12, 15]
Example:
Words = ("spam", "egss") Or
Words = "spam", "eggs"
Example:
Dict = {"ram": 26, "abi":24}
Access: print(list[0]) Access: print(words[0]) Access: print(dict["ram"])
Can contain duplicate
elements
Can contain duplicate
elements. Faster compared
to lists
Cant contain duplicate keys,
but can contain duplicate
values
Slicing can be done Slicing can be done Slicing can't be done
Usage: List is the collection of
data that can be changed
Usage: Tuple is the
collection of data that
cannot be changed
Usage: Dictionaries is used
when logical association
between data is required.
Matrix Addition
a=[[1,1],[1,1]]
b=[[2,2],[2,2]]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)
Matrix Multiplication
a=[[1,1],[1,1]]
b=[[2,2],[2,2]]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
for k in range(len(b)): c[i][j]=c[i][j]+a[i]
[k]*b[k][j]
for i in c:
print(i)
Matrix Transpose
a=[[1,1],[1,1]]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
for i in c:
print(i)
A=[[1,1],[1,1]]
(Or)
A = []
r1 = int(input("Enter rows of A matrix:"))
c1 = int(input("Enter columns of A matrix:"))
for i in range(0, r1):
A.append([])
for j in range(0, c1):
elem = int(input())
A[i].append(elem)
print(A)
B=[[1,1],[1,1]]
(Or)
B = []
r2 = int(input("Enter rows of B matrix:"))
c2=int(input("Enter columns of B matrix:"))
for i in range(0, r2):
B.append([])
for j in range(0, c2):
elem=int(input())
B[i].append(elem)
print(B)
Illustrative Programs
Histogram
def histogram(items):
for n in items :
output=‘ ‘
times=n
while(times>0):
output+='*'
times=times-1
print(output)
histogram([2,5,12,14])
Selection Sort
n = int(input("Enter the number of elements:"))
slist = []
for i in range(0, n) :
element=int(input("Enter element: "))
slist.append(element)
selectionsort(slist)
Selection Sort - Continued
def selectionsort(slist):
for i in range(0,len(slist)):
for j in range(i+1,len(slist)):
if(slist[i]>slist[j]):
temp=slist[i]
slist[i]=slist[j]
slist[j]=temp
print("Sorted List using Selection Sort")
for i in range(0,len(slist)):
print(slist[i],end=" ")
print()
Merge sort
Concept
Students Mark
Statement
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Retail Bill Preparation

Unit 4.pptx python list tuples dictionary

  • 1.
  • 2.
    Lists • A listis a sequence of values of any type, placed within square brackets and with comma separator. [item1, item2,.....,item n] • The values in a list are called elements or sometimes items. • Insertion order preserved. • Duplicate objects are allowed. • Heterogeneous objects are allowed. • List is dynamic because based on our requirement we can increase the size and decrease the size.
  • 3.
    i=[10,20,’a’,’b’,45,’f’] List representation: -ve index +veindex -6 -5 -4 -3 -2 -1 10 20 a b 45 f 0 1 2 3 4 5
  • 4.
    Contd., Output >>>l=[] >>> print(l) >>>print(type(l)) >>>l=[10,20,30,'a','b',40,10,20] >>> print(l) >>> print(type(l)) Empty List [] <class 'list'> Enter list: [10,20,30,'a','b',40,10,20] [10, 20, 30, 'a', 'b', 40, 10,20] <class 'list'>
  • 5.
    Contd., range(start, stop, step) >>>l=list(range(0,10,2)) >>> print(l) String List() >>>Mylist=[“one”,“two”,“three”] for items in Mylist: print(items) >>> s='Learning python is very easy !!!' >>> l=s.split() >>> print(l) Output: [0, 2, 4, 6, 8] one two three ['Learning', 'python', 'is', 'very', 'easy', '!!!']
  • 6.
    List within anotherList • Eg: >>> a=5 >>> b=‘xyz’ >>> c=[a, b] >>> seq=[a, b, c] >>>seq [5, ‘xyz’, [5, ‘xyz’]] >>> l=list([10,20,30,[40,50]]) >>> print(l) [10, 20, 30, [40, 50]]
  • 7.
    Contd., Using for loop range() x=[10,20,'a','b',45,'f'] >>>for i in range(len(x)): print(x[i]) 10 20 a b 45 F
  • 8.
    Accessing Elements ofList: • We can access elements of the list either by using index or by using slice operator(:) 1) By using Index: • List follows zero based indexes. ie index of first element is zero. • List supports both +ve and -ve indexes. • i=[10,20,’a’,’b’,45,’f’] >>> print(l[0]) 10 • >>> print(l[-2]) • 30 45
  • 9.
    Contd., • By usingSlice Operator: Syntax: list2 = list1[start:stop:step] • Start It indicates the Index where slice has to start Default Value is 0 • Stop It indicates the Index where slice has to End Default Value is max allowed Index of List ie Length of the List • Step  increment value Default Value is 1
  • 10.
    Contd., >>> i=[10,20,'a','b',45,'f'] >>>print( i[:5]) >>>print(i[:]) >>>print(i[3:4]) >>>print( i[5:100]) >>> print(i[100]) [10, 20, 'a', 'b', 45] [10, 20, 'a', 'b', 45, 'f'] ['b'] ['f'] Traceback (most recent call last): File "<pyshell#62>", line 1, in <module> i[100] IndexError: list index out of range
  • 11.
    List Index • Indexoperator  [ ] • Index starts with 0. • Index must be an integer. • Nested lists are accessed using Nested Indexing. • Eg: >>>mylist=[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] >>>print(mylist[0])  prints ‘p’ >>>print(mylist[2])  prints t >>>print(mylist[-2])  prints ‘o’ # Nested Lists Example >>>N_list=[“Happy”, [2, 0, 1, 7]] >>>print(N_list) >>>print(N_list[0][1])  prints ‘a’ >>>print(N_list[1][2])  prints 1
  • 12.
    Contd., Lists are mutable:Changeable >>>i=[10,20,'a','b',45,'f'] >>>print(i[4]) 45 >>> i[4]='U' >>> print(i) [10, 20, 'a', 'b', 'U', 'f']
  • 13.
    Contd., >>>i=[10, 20, 'a','b', 'U', 'f'] >>>r=[1,2,3,4,5] >>> l=['q','w','e','r','t','y'] >>> print(i,r,l) [10, 20, 'a', 'b', 'U', 'f'] [1, 2, 3, 4, 5] ['q', 'w', 'e', 'r', 't', 'y'] >>> 'q'in l True >>> 'q' in r False
  • 14.
    Basic List Operations ExpressionResults Description len([1, 2, 3, 4]) 4 Length of the list [1,2,3,4]+[5,6,7,8] [1,2,3,4,5,6,7,8] Concatenation [“Hi!”] * 2 [1,2,3]*2 [“Hi!”, “Hi!”] [1,2,3,1,2,3] Repetition 2 in [1, 2, 3, 4, 5] True Membership for x in [1, 2, 3, 4, 5]: print(x, end=“ ”) 1 2 3 4 5 Iteration
  • 15.
    List Methods Methods Description append()Add an element to the list extend() Add several elements to a list at a time insert() Insert an item at the specified index remove() Removes the specified item from the list pop() Removes and returns the element at the given index clear() Removes all elements from the list index() Returns the index position of the first matched item count() Returns the count of number of items passed as an argument sort() Sort items in a list in ascending order reverse() Reverses the order of the list copy() Copies the list to another list
  • 16.
    append() method • Listsare mutable. i.e. elements can be added or removed as and when needed. • Eg: List=[123, “Python”, “Language”] print(“Original List is: ”, List) List.append(“2019 Batch”) print(“Updated List is: ”, List) Output: Original List is: [123, “Python”, “Language”] Updated List is: [123, “Python”, “Language”, “2019 Batch”]
  • 17.
    Contd., l=[] for i inrange (101): if(i%10)==0: l.append(i) print(l) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
  • 18.
    Deleting the elements •Two ways: 1. del statement if exact element location is known. 2. remove() method if the exact locations are not known. Eg: List=[123, “Python”, “Language”] print(List) del List[0] print(List) OUTPUT: [123, “Python”, “Language”] [“Python”, “Language”]
  • 19.
    remove() method • Eg: List=[10,20, 30, 20, 50, 20] print(List) List.remove(20) print(List) Note that only the first instance of 20 alone was removed. OUTPUT: [10, 20, 30, 20, 50, 20] [10, 30, 20, 50, 20]
  • 20.
    Insert()  The elementsare inserted at a specified position. >>> l=[1,2,3,5,6,7] >>> l.insert(3,4) >>> print(l) >>> print(l) >>> l.insert(10,9) >>> print(l) >>> l.insert(-10,8) >>> print(l) [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 9] [8, 1, 2, 3, 4, 5, 6, 7, 9]
  • 21.
    Extend() Add all itemof one list to another list >>> l=['hai','hello'] >>> m=['good','morning'] >>> l.extend(m) >>> print(l) >>> m.extend(l) >>> print(m) ['hai', 'hello', 'good', 'morning'] ['good', 'morning', 'hai', 'hello']
  • 22.
    append() and extend() •append()  used to add one element at a time to list. • extend()  used to add several elements at a time to list. • Eg: >>>even=[2, 4, 6] >>>print(even)  prints 2 4 6 >>>even.append(8) >>> print(even)  prints 2 4 6 8 >>>even.extend([10, 12, 14]) >>>print(even)  prints 2 4 6 8 10 12 14
  • 23.
    Pop() It removes lastelement of the list This function has return value l=[1,2,3,4,5,6,7,8,9] >>> x=l.pop() >>> print(x) 9 >>> print(l) [1, 2, 3, 4, 5,6, 7, 8] >>> n=[] >>> x=n.pop() Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> x=n.pop() IndexError: pop from empty list
  • 24.
    Advanced List Processing MAP,REDUCE AND FILTER(list comprehension) • MapA Processing pattern that traverses a sequence and performs an operation on each element. • Reduce A Processing pattern that traverses a sequence and accumulates the elements into a single result. • Filter A Processing pattern that traverses a sequence and select the elements that satisfy some criterion.
  • 25.
    Map and reduce t=[9,8,7,6,5,4] tot=0 fori in t: tot=tot+i print(tot) 39 print(sum(t)) 39 (reduce : sequence of steps into one statement)
  • 26.
    filter >>> t=['a','A','b','B','C','c'] >>>l=[] >>> fors in t: if s.islower(): l.append(s) >> print(l) ['a', 'b', 'c']
  • 27.
    List Comprehension >>> l=[x*xfor x in range(11)] >>> print(l) >>> l=[x*x for x in range(1,11)] >>> print(l) >>> l=[x*x for x in range(1,11,2)] >>> print(l) >>> l=[x*x for x in range(0,11,2)] >>> print(l) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [1, 9, 25, 49, 81] [0, 4, 16, 36, 64, 100] Create a list of objects from any inerrable objects. Syntax: VN=[expression for item in list if condition]
  • 28.
    Contd., l=[2**x for xin range(1,6)] >>> print(l) [2, 4, 8, 16, 32] >>> s=[1,4,9,16,25,36,49,64,81,100] >>> l=[x for x in s if(x%2==0)] >>> print(l) [4, 16, 36, 64, 100] words=['hai','hello','good','morning'] >>> l=[w[0] for w in words] >>> print(l) ['h', 'h', 'g', 'm‘]
  • 29.
    List as parameters •In python, arguments are passed by reference. • If any changes are done in the parameter which refers within the function, then the changes also reflects back in the calling function. • When a list to a function is passed, the function gets a reference to the list, access to the original list, but does not create a new copy of list.
  • 30.
    List as parameters defremove(a): a.remove(1) print(a) a=[1,2,3,4,5] remove(a) [2,3,4,5] def insert(a): a. insert(0,30) a=[1,2,3,4,5] insert(a) print(a) [30,2,3,4,5]
  • 31.
    Aliasing and Cloning Cloning: •Cloning means making an exact but separate copy without modifying the original list. • creating a copy of a same list of elements with two different memory locations is called cloning. • Changes in one list will not affect locations of another list. Aliasing: • Creating a copy of a list is called aliasing. • When you create a copy both list will be having same memory location. • Changes in one list will affect another list. • Aliasing refers to having different names for same list values.
  • 32.
    List Aliasing >>>list1 =[10, 20, 30, 40] >>>list2= list1 >>>list1[0] = 5 >>>list1 [5, 20, 30, 40] change made in list1 >>>list2 [5, 20, 30, 40] change in list1 causes a change in list2
  • 33.
    List cloning >>>list1 =[10, 20, 30, 40] >>>list2= list1[:] >>>list2[0] = 5 >>>list1 [10, 20, 30, 40] change not made in list1 >>>list2 [5, 20, 30, 40] change made in list2
  • 34.
    Sum of elementsin list a=[1,2,3,4,5] i=0 sum=0 while i<len(a): sum=sum+a[i] i=i+1 print(sum)
  • 35.
    Home practices –Slice Operator >>> l=[1,2,3,'a','b',4,5] >>> print(l[:]) >>> print(l[::]) >>> print(l[-1:-7]) >>> print(l[-1::-7]) >>> print(l[-1::]) >>> print(l[0::-1]) >>> print(l[::-1]) >>> print(l[::-7]) [1, 2, 3, 'a', 'b', 4, 5] [1, 2, 3, 'a', 'b', 4, 5] [] [5] [5] [1] [5, 4, 'b', 'a', 3, 2, 1] [5]
  • 36.
    Tuples (values)  Tupleassignment  Tuple as return value • Tuple is exactly same as List except that it is immutable. i.e once we creates Tuple object, we cannot perform any changes in that object. • Hence Tuple is Read only version of List. • If our data is fixed and never changes then we should go for Tuple. • Insertion Order is preserved • Duplicates are allowed • Heterogeneous objects are allowed.
  • 37.
    • We canpreserve insertion order and we can differentiate duplicate objects by using index. Hence index will play very important role in Tuple also. • Tuple support both +ve and -ve index. +ve index means forward direction (from left to right) and - ve index means backward direction (from right to left) • We can represent Tuple elements within Parenthesis and with comma separator.
  • 38.
    Home practices –Slice Operator -TUPLE >>> a=(1,2,3,4) >>> print(a[:]) >>> print(a[:-1]) >>> print(a[::-1]) >>> print(a[-4::]) >>> print(a[:0:]) >>> print(a[:2]) >>> print(a[2::]) >>> print(a[1:3]) >>> print(a[-4:-2]) >>> print(a[-2:]) >>> print(a[-3:-1]) (1, 2, 3, 4) (1, 2, 3) (4, 3, 2, 1) (1, 2, 3, 4) () (1, 2) (3, 4) (2, 3) (1, 2) (3, 4) (2, 3)
  • 39.
    methods example description list() a=(1,2,3,4,5) it convert the a=list(a) given tuple into list. print(a) [1, 2, 3, 4, 5] tuple( ) a=[1,2,3,4,5] it convert the given a=tuple(a) list into tuple. print(a) (1, 2, 3, 4, 5)
  • 40.
    Benefit of Tuple: •Tuples are faster than lists. • If the user wants to protect the data from accidental changes, tuple can be used. • Tuples can be used as keys in dictionaries, while lists can't. Operations on Tuples: • Indexing • Slicing • Concatenation • Repetitions • Membership • Comparison
  • 41.
    Operations Examples Description Creatinga tuple a=(20,40,60,”apple”,”ball”) Creating the tuple with elements of different data types. Indexing print(a[0]) 20 a[2] 60 Accessing the item in the position 0 Accessing the item in the position 2 Slicing print(a[1:3]) (40,60) Displaying items from 1st till 2nd. Concatenation b=(2,4) >>>print(a+b) (20,40,60,”apple”,”ball”,2,4) Adding tuple elements at the end of another tuple elements Repetition print(b*2) (2,4,2,4) repeating the tuple in n no of times Membership a=(2,3,4,5,6,7,8,9,10) 5 in a True 100 in a False 2 not in a False Returns True if element is present in tuple. Otherwise returns false. Comparison a=(2,3,4,5,6,7,8,9,10) b=(2,3,4) a==b False a!=b True Returns True if all elements in both elements are same. Otherwise returns false
  • 42.
    >>> t=10,20,30,40 >>> print(t)(10, 20, 30, 40) >>> print(type(t)) <class 'tuple'> >>> t=() >>> print(t) () >>> print(type(t)) <class 'tuple'> >>> t=(10) >>> print(type(t)) <class 'int'> >>> t=(10,) >>> print(t) (10,) >>> print(type(t)) <class 'tuple'>
  • 43.
    Tuple Vs. Immutability •As we can’t update the values of tuple it is immutable. >>> t=10,20,30,40 >>> t[1]=90 Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> t[1]=90 TypeError: 'tuple' object does not support item assignment
  • 44.
    Mathematical Operators fortuple We can apply + and * operators for tuple Concatenation operator (+) >>>t=10,20,30,40 >>> t1=50,60,70,80,90 >>> print(t+t1) (10, 20, 30, 40, 50, 60, 70, 80, 90) Multiplication / Repetition Operator (**) >>>print(t*2) (10, 20, 30, 40, 10, 20, 30, 40)
  • 45.
    Tuple Assignment a,b=10, 20 >>>a,b=10,20 >>> print(a) 10 >>> print(b) 20 >>> a,b=b,a >>> print(a) 20 >>> print(b) 10
  • 46.
    Tuple as returnvalue • The function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. • Divmod function takes two arguments input and returns a tuple of two values. a=divmod(45,5) >>> print(a) (9, 0)
  • 47.
    Tuple as ReturnValues def div(a,b): r=a%b q=a//b return(r,q) a=int(input("enter a value:")) b=int(input("enter b value:")) r,q=div(a,b) print("reminder:",r) print("quotient:",q)
  • 48.
    Dictionary {key:value} • Wecan use List, Tuple to represent a group of individual objects as a single entity. • If we want to represent a group of objects as key- value pairs then we should go for Dictionary. • Duplicate keys are not allowed but values can be duplicated. • Heterogeneous objects are allowed for both key and values. • Dictionaries are mutable • Dictionaries are dynamic • Indexing and slicing concepts are not applicable
  • 49.
    Real Time Example •Eg: Telephone Diary • We may remember only the names of the contacts and not their numbers. • So storing it in a dictionary would be easier to retrieve the value with given name key.
  • 50.
    How to createdictionary? >>> d={} >>> print(d) {} >>> print(type(d)) <class 'dict'> >>> d=dict() >>> print(d) {} >>> print(type(d)) <class 'dict'>
  • 51.
    >>> d[1]='Hello' >>> d[2]='Hai' >>>d[3]='Everyone' >>> d[5]='Have Nice Day' >>> print(d) {1: 'Hello', 2: 'Hai', 3: 'Everyone', 5: 'Have Nice Day'}
  • 52.
    How to accessdata from dictionary We can access data by using keys D={1: 'Hello', 2: 'Hai', 3: 'Everyone', 5: 'Have Nice Day'} >>> print(d[3]) Everyone >>> print(d[0]) Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> print(d[0]) KeyError: 0 >>> print(d.keys()) dict_keys([1, 2, 3, 5]) >>> print(d.values()) dict_values(['Hello', 'Hai', 'Everyone', 'Have Nice Day'])
  • 53.
    How to updateDictionaries? • d[key]=value • If the key is not available then a new entry will be created with the specified key-value pair. • If the key already available, then the old value will be replaced with new value. d={1: 'Hello', 2: 'Hai', 3: 'Everyone', 5: 'Have Nice Day'} >>> d[3]='buddy' >>> print(d) {1: 'Hello', 2: 'Hai', 3: 'buddy', 5: 'Have Nice Day'} >>> print(d) {1: 'Hello', 2: 'Hai', 3: 'buddy', 5: 'Have Nice Day', 4: 24}
  • 54.
    How to deleteelements from dictionaries del d[key] -> deletes an entry stored in a specified key. d={1: 'Hello', 2: 'Hai', 3: 'buddy', 5: 'Have Nice Day', 4: 24} >>> del d[5] >>> print(d) {1: 'Hello', 2: 'Hai', 3: 'buddy', 4: 24} >>> del d[6] Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> del d[6] KeyError: 6
  • 55.
    d.clear() -> removeall entries from dictionaries >>>d= {1: 'Hello', 2: 'Hai', 3: 'buddy', 4: 24} >>> d.clear() >>> print(d) {} >>> d={1: 'Hello', 2: 'Hai', 3: 'buddy', 4: 24} >>> del d >>> print(d) Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> print(d) NameError: name 'd' is not defined
  • 56.
    Operations on dictionaries OperationsExample Description Creating a dictionary >>> a={1:"one",2:"two"} >>> print(a) {1: 'one', 2: 'two'} Creating the dictionary with elements of different data types. accessing an element >>> a[1] 'one' >>> a[0] KeyError: 0 Accessing the elements by using keys. Update >>> a[1]="ONE" >>> print(a) {1: 'ONE', 2: 'two'} Assigning a new value to key. It replaces the old value by new value. add element >>> a[3]="three" >>> print(a) {1: 'ONE', 2: 'two', 3: 'three'} Add new element in to the Dictionary with key. membership a={1: 'ONE', 2: 'two', 3: 'three'} >>> 1 in a True >>> 3 not in a False Returns True if the key is present in dictionary. Otherwise returns false.
  • 57.
    Methods in dictionaries MethodExample Description a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} >>> b=a.copy() >>> print(b) {1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the dictionary. here copy of dictionary ‟a‟ get stored in to dictionary „b‟ a.items() >>> a.items() dict_items([(1, 'ONE'), (2, 'two'), (3,'three')]) Return a new view of the dictionary's items. It displays a list of dictionary‟s (key, value) tuple pairs. a.keys() >>> a.keys() dict_keys([1, 2, 3]) It displays list of keys in a dictionary a.values() >>> a.values() dict_values(['ONE', 'two', 'three']) It displays list of values in dictionary a.pop(key) >>> a.pop(3) 'three' >>> print(a) {1: 'ONE', 2: 'two'} Remove the element with key and return its value from the dictionary.
  • 58.
    a.update(dictionary) >>> b={4:"four"} >>>a.update(b) >>> print(a) {1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} It will add the dictionary with the existing dictionary fromkeys() >>> key={"apple","ball"} >>> value="for kids" >>> d=dict.fromkeys(key,value) >>> print(d) {'apple': 'for kids', 'ball': 'for kids'} t creates a dictionary from key and values len(a) {'apple': 'for kids', 'ball': 'for kids'} >>>lena(a) 3 It returns the length of the list. clear() a={1: 'ONE', 2: 'two', 3: 'three'} >>>a.clear() >>>print(a) >>>{ } Remove all elements form the dictionary. del(a) a={1: 'ONE', 2: 'two', 3: 'three'} >>> del(a) It will delete the entire dictionary.
  • 59.
    List Tuple Dictionary Alist is mutable A tuple is immutable Lists are dynamic Tuples are fixed size in nature List are enclosed in brackets[ ] and their elements and size can be changed Tuples are enclosed in parenthesis ( ) and cannot be updated Tuples are enclosed in curly braces { } and consist of key: value Homogenous Heterogeneous Homogenous Example: List = [10, 12, 15] Example: Words = ("spam", "egss") Or Words = "spam", "eggs" Example: Dict = {"ram": 26, "abi":24} Access: print(list[0]) Access: print(words[0]) Access: print(dict["ram"]) Can contain duplicate elements Can contain duplicate elements. Faster compared to lists Cant contain duplicate keys, but can contain duplicate values Slicing can be done Slicing can be done Slicing can't be done Usage: List is the collection of data that can be changed Usage: Tuple is the collection of data that cannot be changed Usage: Dictionaries is used when logical association between data is required.
  • 60.
    Matrix Addition a=[[1,1],[1,1]] b=[[2,2],[2,2]] c=[[0,0],[0,0]] for iin range(len(a)): for j in range(len(b)): c[i][j]=a[i][j]+b[i][j] for i in c: print(i)
  • 61.
    Matrix Multiplication a=[[1,1],[1,1]] b=[[2,2],[2,2]] c=[[0,0],[0,0]] for iin range(len(a)): for j in range(len(b)): for k in range(len(b)): c[i][j]=c[i][j]+a[i] [k]*b[k][j] for i in c: print(i)
  • 62.
    Matrix Transpose a=[[1,1],[1,1]] c=[[0,0],[0,0]] for iin range(len(a)): for j in range(len(a)): c[i][j]=a[j][i] for i in c: print(i)
  • 63.
    A=[[1,1],[1,1]] (Or) A = [] r1= int(input("Enter rows of A matrix:")) c1 = int(input("Enter columns of A matrix:")) for i in range(0, r1): A.append([]) for j in range(0, c1): elem = int(input()) A[i].append(elem) print(A)
  • 64.
    B=[[1,1],[1,1]] (Or) B = [] r2= int(input("Enter rows of B matrix:")) c2=int(input("Enter columns of B matrix:")) for i in range(0, r2): B.append([]) for j in range(0, c2): elem=int(input()) B[i].append(elem) print(B)
  • 65.
  • 66.
    Histogram def histogram(items): for nin items : output=‘ ‘ times=n while(times>0): output+='*' times=times-1 print(output) histogram([2,5,12,14])
  • 67.
    Selection Sort n =int(input("Enter the number of elements:")) slist = [] for i in range(0, n) : element=int(input("Enter element: ")) slist.append(element) selectionsort(slist)
  • 68.
    Selection Sort -Continued def selectionsort(slist): for i in range(0,len(slist)): for j in range(i+1,len(slist)): if(slist[i]>slist[j]): temp=slist[i] slist[i]=slist[j] slist[j]=temp print("Sorted List using Selection Sort") for i in range(0,len(slist)): print(slist[i],end=" ") print()
  • 69.
  • 70.
    Students Mark Statement sub1=int(input("Enter marksof the first subject: ")) sub2=int(input("Enter marks of the second subject: ")) sub3=int(input("Enter marks of the third subject: ")) sub4=int(input("Enter marks of the fourth subject: ")) sub5=int(input("Enter marks of the fifth subject: ")) avg=(sub1+sub2+sub3+sub4+sub4)/5 if(avg>=90): print("Grade: A") elif(avg>=80&avg<90): print("Grade: B") elif(avg>=70&avg<80): print("Grade: C") elif(avg>=60&avg<70): print("Grade: D") else: print("Grade: F")
  • 71.