Python Notes 3
Python Notes 3
PDF - 3
LISTS
A list is a standard data type of Python that can store a sequence of values
belonging to any data type . It is an ordered set of values enclosed in square brackets
[ ] . Values in the list can be modified. i.e. it is mutable.
As it is a set of values, we can use index in square brackets [ ] to identify a value
belonging to it. The values that make up a list are called it elements .i.e. For accessing
an element of the list, indexing is used.
Syntax:
variable name[index] (variable name is name of the list)
Examples:-
[] # empty list
[ 1, 2, 3 ] # list of integers
[1, 2.5, 3.7, 9 ] # integers and float values
[ 'a', 'b' ,'c' ] # character list
['a', 1, 3.5, 'zero'] # mixed value types
['one' , 'two', 'three'] # list of strings
ACCESSING LIST
>>> L = [ 'a', 'e', 'i', 'o', 'u']
0 1 2 3 4
L a e i o u
-5 -4 -3 -2 -1
L[0] --> 'a'
L[2 : 4] --> ['i' , 'o'] # character at index number 4 will not be retrieved
L[-2] --> 'o' # character at index number -2
len(L) --> 5 # Number of items in the list
Page 1 of 13
CREATING A LIST
1) L1 = [ 1, 2, 3, 4]
2) L2 = list('1234')
print(L2)
TRAVERSING A LIST
1) for a in [ 1, 2, 3, 4]:
print(a)
Output-->
1
2
3
4
2) L = [1, 2, 3, 4]
for a in L:
print(a)
Output-->
1
2
3
4
NOTE: The loop variable a in the above loop will be assigned the list elements one at
a time
Page 2 of 13
3) Using indexes of elements to access them ( range( ) and len( ) functions)
L = [ 1, 2, 3, 4]
length = len(L)
for a in range( 0, length) : # can be also written as--> for a in range(len(L)):
print(L[a])
Output -->
1
2
3
4
LIST OPERATIONS
1) JOINING LISTS:- The concatenation operator is used to join two lists.
>>> lst1 = [1, 3, 5]
>>> lst2 = [6, 7, 8]
>>> lst1 + lst2
[1, 3, 5, 6, 7, 8]
>>> lst = lst1 + lst2
>>> lst
[1, 3, 5, 6, 7, 8]
NOTE:- The operator + when used with lists requires that both the operands must be
of list types.
i.e.
>>> lst1 + 4
TypeError: can only concatenate list (not "int") to list
3) SLICING A LIST:-
Slicing operations allow us to create new list by taking out elements from an existing
list.
Syntax:-
lst = L[start : stop]
Page 3 of 13
The above statement will create a list slice namely L having elements of list lst on
indexes start , start + 1, start + 2,.............stop - 1.(i.e. not including stop)
or
L[start : stop : step]
Use slice steps if you want to extract not consecutive but every other element of the list.
Examples:
1) >>> lst = [11, 13, 14, 17, 19, 20, 23, 25, 30]
>>> L1 = lst[2 : 6] # value at index 6 will not be retrieved
>>> L1
[14, 17, 19, 20]
10) >>> lst [ : : -1] #Access list in the reverse order using negative step size
[30, 25, 23, 20, 19, 17, 14, 13, 11]
Page 4 of 13
4) MEMBERSHIP:-
The membership operator in checks if the element is present in the list and returns
True, else returns False.
>>> L1 = ['blue' , 'pink', 'green']
>>> 'green' in L1
True
>>> 'green' not in L1
False
extend() Adds multiple >>> L1 = [ 13, 18, 11, 16, 18, 14]
elements(given in the form of >>> L2=[50, 60]
a list) to a list. >>> L1.extend(L2)
>>> L1
[13, 18, 11, 16, 18, 14, 50, 60]
i.e. List.remove(<value>)
Note:- pop() method will not only delete the value for the mentioned index but
also returns the deleted value.
clear() Removes all the items from >>> L1 = [ 13, 18, 11, 16, 18, 14]
the list and the list becomes >>> L1.clear()
empty list after this function. >>> L1
This function returns nothing. []
count() Returns the number of >>> L1 = [ 13, 18, 11, 16, 18, 14]
times a given element >>> L1.count(18)
appears in the list 2
>>> L1.count(72)
0
reverse() Reverses the order of >>> T1 = ['a', 'e', 'i', 'o', 'u']
elements in the given list >>> T1.reverse()
>>> T1
['u', 'o', 'i', 'e', 'a']
sort() Sorts the elements of the >>> T2 = ['Tiger','Zebra','Lion','Cat',
given list in place 'Elephant' ,'Dog']
>>> T2.sort()
>>> T2
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger',
'Zebra']
>>> L1 = [34,66,12,89,28,99]
>>> L1.sort(reverse=True)
>>> L1
[99, 89, 66, 34, 28, 12]
Page 6 of 13
Q- Program to find the maximum element from a list of element along with its
index in the list
Page 7 of 13
Q- Program to find the minimum element from a list of element along with its
index in the list
Page 8 of 13
Enter input : [2,3,5,7,12,1]
Enter element to be searched for: 7
Element found at index location 3
******************************************************************
3) marks['sci'] = 93
marks['sst'] = 98
marks
{'eng': 96, 'hindi': 90, 'maths': 92, 'sci': 93, 'sst': 98}
>>> marks['maths'] = 95
>>> marks
{'eng': 96, 'hindi': 90, 'maths': 95, 'sci': 93, 'sst': 98}
Page 9 of 13
TRAVERSING A DICTIONARY
We can access each item of the dictionary or traverse a dictionary using for loop.
dict1 = { 'eng': 96 , 'hindi' : 90 , 'maths' : 92 }
Method 1:
for key in dict1:
print(key,':',dict1[key] ) # key will access the key and dict1[key] will access the value
Output-->
eng : 96
hindi : 90
maths : 92
Method 2:
for key,value in dict1.items():
print(key,':',value)
Output-->
eng : 96
hindi : 90
maths : 92
DELETING ELEMENTS
There are two methods for deleting elements from a dictionary.
(i) Using del command:-
>>> emp={'name':'Vividh', 'salary' : 50000 , 'age' : 24}
>>> del emp['age']
>>> emp
{'name': 'Vividh', 'salary': 50000}
Page 10 of 13
24
>>> emp
{'name': 'Vividh', 'salary': 50000}
Note:- pop() method will not only delete the key:value pair for the mentioned key but
also returns the corresponding value.
values() Returns all the values in the >>> emp = {'name':'Vividh', 'salary'
dictionary as a sequence(a list) : 50000 , 'age' : 24}
>>> emp.values()
dict_values(['Vividh', 50000, 24])
update() This method merges key:value >>>emp1={'name':'Vividh',
pairs from the new dictionary 'salary' : 50000 , 'age' : 24}
into the original dictionary,
adding or replacing as needed. >>> emp2={'name':'Darsh' ,
'salary' : 72000 , 'dept': 'IT'}
Page 11 of 13
The items in the new dictionary
are added to the old one and
override any items already >>> emp1.update(emp2)
there with the same keys. >>> emp1
{'name': 'Darsh', 'salary': 72000,
'age': 24, 'dept': 'IT'}
>>> emp2
{'name': 'Darsh', 'salary': 72000,
'dept': 'IT'}
clear() Removes all items from the >>> emp.clear()
dictionary and dictionary >>> emp
empty {}
Output-->
How many states : 2
Enter the state name Maharashtra
Enter the state capital : Mumbai
Enter the state name Assam
Enter the state capital : Dispur
The dictionary is :
{' Maharashtra': 'Mumbai', ' Assam': 'Dispur'}
Page 12 of 13
Q - Create a dictionary of students to store names and marks obtained in 5
subjects.
#Dictionary of students to store names and marks obtained in 5 subjects.
n = int(input("Enter number of students : "))
studentInfo = {}
for a in range(n) :
key = input("Enter the student's name")
value = int(input("Enter the marks obtanined : "))
studentInfo[key] = value
print(" The dictionary is : ")
print(studentInfo)
Output-->
Enter number of students : 2
Enter the student's name Shlok
Enter the marks obtanined : 74
Enter the student's name Anita
Enter the marks obtanined : 85
The dictionary is :
{' Shlok': 74, ' Anita': 85}
Note :
1. The above mentioned should be written in the Informatics Note book as a continuity
of the previous notes. ( No Printout Allowed )
2. The entire topic will be discussed in the class.
3. Mistakes / corrections ( if any ) will be rectified during class room discussion.
******************************************************************
Page 13 of 13