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