0% found this document useful (0 votes)
18 views

Python Notes 3

Lists are a mutable data type in Python that can store sequences of values of any data type. Values in a list are ordered and can be accessed using indexes. Lists support common operations like accessing elements, slicing, concatenation, membership testing, and several built-in methods. Common list methods include append() to add elements, pop() and remove() to delete elements, sort() to sort elements, and reverse() to reverse the order of elements.

Uploaded by

Surya Tejas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Notes 3

Lists are a mutable data type in Python that can store sequences of values of any data type. Values in a list are ordered and can be accessed using indexes. Lists support common operations like accessing elements, slicing, concatenation, membership testing, and several built-in methods. Common list methods include append() to add elements, pop() and remove() to delete elements, sort() to sort elements, and reverse() to reverse the order of elements.

Uploaded by

Surya Tejas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit 2: INTRODUCTION TO PYTHON

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)

['1' ,'2', '3', '4']


3) >>> L3 = list(input("Enter the list elements: "))
>>>Enter the list elements: 1234
>>> L3

['1', '2', '3', '4']

4) >>> L4 = eval(input("Enter the list elements: "))


>>>Enter the list elements: [1,2,3,4]
>>> L4
[1, 2, 3, 4]
NOTE:- eval() is used to evaluate the type and return the result.

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

2) REPEATING OR REPLICATING LISTS:-


In Python, * operator (asterisk) is used to replicate a list specified number of times.
>>> lst = [2, 4, 6]
>>> lst * 2
[2, 4, 6, 2, 4, 6]

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]

2) >>> L2 = lst[2 : -3]


>>> L2
[14, 17, 19, 20]
3) >>> lst[ -6 : -1 ]
[17, 19, 20, 23, 25]
4) >>> lst[ 2 : 20] # Second index is out of range
[14, 17, 19, 20, 23, 25, 30]
5) >>> lst[ 20 : 10 ] # First index > second index
[] # results an empty list

6) >>> lst[ : 5] # first index missing


[11, 13, 14, 17, 19] # return sublist from index 0 to 4
7) >>> lst[4:] # second index missing
[19, 20, 23, 25, 30] # return sublist from index 4 to the last index
# value(last value included)
8) >>> lst[0 : 6: 2] # Slicing with a given step size
[11, 14, 19]
9) >>> lst[ : : 2] # both first and last index missing and step size 2
[11, 14, 19, 23, 30] # on entire list

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

LIST METHODS AND BUILT IN FUNCTIONS


Python offers many built in functions and methods for list manipulation.
METHOD DESCRIPTION EXAMPLE
index() Returns the index of first >>> L1 = [ 13, 18, 11, 16, 18, 14]
matched item from the list
>>> L1.index(18)

append() Adds an item to the end of >>> L1


the list. A list can also be [13, 18, 11, 16, 18, 14, ['a', 'b']]
appended as an element to an >>> L1 = [ 13, 18, 11, 16, 18, 14]
>>> L1.append(15)
existing list
>>> L1
Note:- append() does not [13, 18, 11, 16, 18, 14, 15]
return the new list, just >>> L1.append([50, 60])
>>> L1
modifies the original.
[13, 18, 11, 16, 18, 14, 15, [50, 60]]

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]

insert() Inserts an element at a >>> T1=['a','e','u']


particular index in the list >>> T1.insert(2, 'i')
>>> T1
i.e. ['a', 'e', 'i', 'u']
Note:- inserts element 'i' at index 2
List.insert(<index>,<item>)

pop() Returns the element whose >>> T1=['a','e','k','i','u']


index is passed as argument >>> T1.pop(2)
'k'
Page 5 of 13
to this function and also >>> T1
removes it from the list. If ['a', 'e', 'i', 'u']
no argument is given, then >>> ele = T1.pop()
>>> T1
it returns and removes the
['a', 'e', 'i']
last element of the list >>> ele
'u'
remove() Removes the given element >>> T1=['a','e','a','i','o','u']
from the list. If the element >>> T1.remove('a')
is present multiple times, >>> T1
['e', 'a', 'i', 'o', 'u']
only the first occurrence is
>>> T1.remove('k')
removed. If the element is ValueError: list.remove(x): x not in
not present, then list
ValueError is generated.

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

lst=eval(input("Enter list :"))


length = len(lst)
max_ele = lst[0]
for i in range(1,length):
if lst[i] > max_ele:
max_ele = lst[i]
print("Given list is : ", lst)
print("The maximum value in the given list is :", max_ele)
Output-->
Enter list : [13, 34, 11, 67]
Given list is : [13, 34, 11, 67]
The maximum value in the given list is : 67
Execution steps (for reference):-
lst = [13, 34, 11, 67]
length = 4
max_ele = lst[0] = 13
1) i = 1 ( for 1 in range(1, 4))
if 34 > 13 --> Condition returns True
max_ele = 34
2) i = 2 ( for 2 in range(1, 4))
if 11 > 34 --> Condition returns False , NO ACTION
3) i =3 ( for 3 in range(1, 4))
if 67 > 34 --> Condition returns True
max_ele = 67
Note:- Loop will get executed only till i =3 (i.e. Stop value - 1)

Page 7 of 13
Q- Program to find the minimum element from a list of element along with its
index in the list

lst=eval(input("Enter list :"))


length = len(lst)
min_ele = lst[0]
for i in range(1 , length):
if lst[i] < min_ele:
min_ele = lst[i]
print("Given list is : ", lst)
print("The minimum value in the given list is :", min_ele)
Output-->
Enter list :[13,34,22,11,67]
Given list is : [13, 34, 22, 11, 67]
The minimum value in the given list is : 11

Q - Program to search for an element from the given list of numbers:-

lst = eval(input("Enter input : "))


length = len(lst)
element = int(input("Enter element to be searched for: "))
flag = False
ele_index = None
for i in range( 0, length) :
if element == lst[i]:
flag = True
ele_index = i
if flag == True:
print("Element found at index location ", ele_index)
else:
print("Element not present in the given list")
Output-->

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

DICTIONARY DATA TYPE IN PYTHON


Dictionary data type in Python are unordered collections with elements in form of a
key:value pairs that associate keys to values.
Dictionary is created using curly { } brackets.
Dictionaries are mutable which implies that the contents of the dictionary can be
changed after it has been created.
Each of the keys within a dictionary must be unique.
Syntax:
my_dict = { 'key1' : 'value1' , 'key2' : 'value2', ..........'keyn' : 'valuen'}

CREATING AND ADDING ELEMENTS TO DICTIONARIES


1) marks = { 'eng': 96 , 'hindi' : 90 , 'maths' : 92 }

2) marks = { } # empty dictionary


marks = dict() # empty dictionary

3) marks['sci'] = 93
marks['sst'] = 98
marks
{'eng': 96, 'hindi': 90, 'maths': 92, 'sci': 93, 'sst': 98}

UPDATING / MODIFYING EXISITNG DICTIONARY


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

>>> del emp['dept']


KeyError: 'dept'

(ii) Using pop() method:-


>>> emp={'name':'Vividh', 'salary' : 50000 , 'age' : 24}
>>> emp.pop('age')

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.

DICTIONARY METHODS AND BUILT IN FUNCTIONS


METHOD DESCRIPTION EXAMPLES
len() Return the length(i.e. count of emp = {'name':'Vividh', 'salary' :
element[key:value pairs] in the 50000 , 'age' : 24}
dictionary >>> len(emp)
3
get() Returns the value >>> emp = {'name':'Vividh', 'salary'
corresponding to the key : 50000 , 'age' : 24}
passed as the argument.
If the key is not present in the >>> emp.get('salary')
dictionary it will return 50000
nothing. >>> emp.get('dept') #No output
>>>
items() Returns all of the items in the emp = {'name':'Vividh', 'salary' :
dictionary as a 50000 , 'age' : 24}
sequence(key,value) tuples. myList = emp.items()
for x in myList:
print(x)
Output-->
('name', 'Vividh')
('salary', 50000)
('age', 24)
keys() Returns all the keys in the >>> emp = {'name':'Vividh', 'salary'
dictionary as a sequence of : 50000 , 'age' : 24}
keys(a list) >>> emp.keys()
dict_keys(['name', 'salary', 'age'])

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

Q- Create a dictionary to store names of states and their capitals.


# Dictionary to store names of states and their capitals.
n = int(input("How many states : "))
capitalInfo = {}
for a in range(n) :
key = input("Enter the state name")
value = input("Enter the state capital : ")
capitalInfo[key] = value
print(" The dictionary is : ")
print(capitalInfo)

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}

************* COMPLETED THE ABOVE TOPIC ***************

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

You might also like