PYTHON LISTS
LEARNING OBJECTIVES
At the end of this chapter students will be able to understand
Declaring/creating list
Accessing list elements
Indexing method
List slicing method
Adding elements to a list
Insert method
Append method
Extend method
Updating list
Deleting elements from list
Pop method
Del method
Del method with slicing
Remove method
Searching list
List operators
List functions
len()
max()
min()
count()
LIST
A list is a collection of comma-separated values (items) within square brackets.
Values in the list can be modified, i.e. it is mutable.
The values that make up a list are called its elements.
Elements in a list need not be of the same type.
DECLARING/CREATING LIST
Lists can be created by putting comma separated values/items within square brackets.
EXAMPLES
list1=[100, 200, 300, 400, 500]
list2=["Raman", 100, 200, 300, "Ashwin"]
list3=['A', 'E', 'I', 'O', 'U']
List4=[] #empty list
CREATING A LIST FROM ALREADY EXISTING LIST
list5=list1[:]
list5 is a copy of list1
list5=[100, 200, 300, 400, 500]
list6=list2[1:4]
list6 will contain elements 1,2,3 of list2
list6=[100, 200, 300]
list7=list1
list7 will contain all elements of list1
list7=[100, 200, 300, 400, 500]
ACCESSING LIST ELEMENTS
INDEXING METHOD
Elements of a list can be accessed using an indexing method.
List indices start at 0.
The list index has to be a positive or negative integer value or an expression which
evaluates to an integer value. Positive value of index means counting forward from
beginning of the list and negative value means counting backward from end of the list.
An Index Error appears, if we try to access element that does not exist in the list.
If the total number of elements in the list is max, then:
Index value
element in the list
0, -max
1st
1, -max+1
2nd
2, -max+2
3rd
........
max-2, -2
2nd last
max-1, -1
last
Considering the above examples:
list1
list2
list3
list1[2]
300
list2[4]
Ashwin
list3[-1]
list1[1]
100
LIST SLICING METHOD
Slicing is used to retrieve a subset of values. A slice of a list is basically its sub-list. The
syntax used for slicing is:
SYNTAX
list [start: stop: step]
where
start is the starting point
stop is the stopping point
step is the step size - also known as stride
NOTE:
If you omit first index, slice starts from “0‟ and omitting of stop will take it to end.
Default value of step is 1.
It includes the first element but excludes the last element.
EXAMPLE
Consider a list z1 with values
z1=[121, 451.78, "KABIR", "RAMESH", 890, 453.90]
z1[:]
121, 451.78, "KABIR", "RAMESH", 890, 453.90
z1[2:5]
['KABIR', 'RAMESH', 890]
z1[:5]
[121, 451.78, 'KABIR', 'RAMESH', 890]
z1[3:]
['RAMESH', 890, 453.9]
z1[::2]
[121, 'KABIR', 890] (from beginning till end in step 2)
z1[::-2]
[453.9, 'RAMESH', 451.78] (from end till beginning in step 2)
z1[-5:-2]
[451.78, 'KABIR', 'RAMESH']
z1[5:2:-1]
[453.9, 890, 'RAMESH']
z1[-2:-5:-1]
[890, 'RAMESH', 'KABIR']
z1[-2:-5:-2]
[890, 'KABIR']
ADDING ELEMENTS TO A LIST
We can use the method insert, append and extend to add elements to a List.
INSERT METHOD
SYNTAX
list_name.insert(index_number, value)
where:
list_name: is the name of the list
index_number: is the index where the new value is to be inserted
value: is the new value to be inserted in the list
EXAMPLE
Consider a list z1 with values
z1=[121, 451.78, "KABIR", "RAMESH", 890, 453.90]
z1.insert(4, "KIRTI")
After this statement the list z1 will look like:
[121, 451.78, 'KABIR', 'RAMESH', 'KIRTI', 890, 453.9]
The value "KIRTI" was inserted at the index 4 in the list and all the other elements were
shifted accordingly.
APPEND METHOD
Append method is used to add an element at the end of the list.
SYNTAX
list_name.append (value)
where:
list_name: is the name of the list
value: is the new value to be inserted in the list
EXAMPLE
z1.append(10)
After this statement the list z1 will look like:
[121, 451.78, 'KABIR', 'RAMESH', 'KIRTI', 890, 453.9,10]
EXTEND METHOD
Extend method is used to add one or more element at the end of the list.
SYNTAX
list_name.extend (value(s))
where:
list_name: is the name of the list
value(s): is/are the new value(s) to be inserted in the list
EXAMPLE
z1.extend([20,30])
After this statement the list z1 will look like:
[121, 451.78, 'KABIR', 'RAMESH', 'KIRTI', 890, 453.9, 10, 20, 30]
This method can also be used to add elements of another list to the existing one.
EXAMPLE
Consider the following Python script:
list1=[100, 200, 300, 400, 500]
list2=["Raman", 100, "Ashwin"]
list1.extend(list2)
print(list1)
OUTPUT
[100, 200, 300, 400, 500, 'Raman', 100, 'Ashwin']
here list2 is added at the end of the list list1.
UPDATING LIST
Updating means modifying or changing the elements of a list. It is possible to modify a
single element or a part of list.
EXAMPLE
list1=[100, 200, 300, 400, 500]
list2=["Raman", 100, "Ashwin"]
list3=['A', 'E', 'I', 'O', 'U']
list1[2]=700
print(list1)
OUTPUT
[100, 200, 700, 400, 500]
For updating multiple elements list slice is used. Consider the following list
>>> list1=[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> list1[2:5]=[90]
>>> print(list1)
OUTPUT
[100, 200, 90, 'Raman', 100, 'Ashwin']
EXPLANATION
Here list1[2], list1[3] and list1[4] elements will be replaced by the element 90 thus
instead of elements 50, 400, 500 list1 will contain 90.
>>> list2[2:5]=['K']
>>> print(list2)
OUTPUT
['A', 'E', 'K']
DELETING ELEMENTS FROM LIST
We can use the methods del, remove or pop to delete elements to a List.
POP METHOD
It removes the element from the specified index, and also return the element which was
removed.
SYNTAX
list_name.pop(index_value)
EXAMPLE 1
>>> list1 =[100, 200, 90, 'Raman', 100, 'Ashwin']
>>> list1.pop(2)
OUTPUT
90
EXAMPLE 2
>>> print(list1)
OUTPUT
[100, 200, 'Raman', 100, 'Ashwin']
The last element is deleted if no index value is provided in pop ( ).
EXAMPLE 1
>>>list1.pop()
OUTPUT
'Ashwin'
EXAMPLE 2
>>>print(list1)
OUTPUT
[100, 200, 'Raman', 100]
DEL METHOD
The del method removes the specified element from the list, but it does not return the
deleted value.
SYNTAX
del list_name[index_value]
EXAMPLE
>>> list1=[100, 200, 'Raman', 100]
>>> del list1[2]
>>> print(list1)
OUTPUT
[100, 200, 100]
Here the element at index number 2 i.e. 'Raman' has been deleted.
WE can also give negative index value with del.
EXAMPLE
>>>list1=[100, 200, 'Raman', 100, 'Ashwin']
>>> del list1[-1]
>>> print(list1)
OUTPUT
[100, 200, 'Raman', 100]
Here the last element is deleted from the list.
DEL METHOD WITH SLICING
EXAMPLE
>>> list1= [100, 200, 50, 500, 'Raman', 100, 'Ashwin']
>>> del list1[2:4]
>>> print(list1)
OUTPUT
[100, 200, 'Raman', 100, 'Ashwin']
Here 2nd and 3rd elements are deleted from the list.
REMOVE METHOD
The remove method is used when the index value is unknown and the element to be
deleted is known.
SYNTAX
list_name.remove(element_value)
EXAMPLE
>>> list1=[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> list1.remove(400)
>>> print(list1)
OUTPUT
[100, 200, 50, 500, 'Raman', 100, 'Ashwin']
here element with value 400 is removed from the list list1.
SEARCHING LIST
Lists can easily be searched for values using the index method that expects a value that
is to be searched. The output is the index at which the value is kept.
SYNTAX
list_name.index(element)
EXAMPLE
>>> list1=[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> list1.index(400)
OUTPUT
EXPLANATION
Here we are searching the list lst1 for value 400.The answer is 3 as the element 400 is
present the index value 3.
If the value, we are searching in a list is not found then an error is displayed.
EXAMPLE
>>> list1=[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> list1.index(700)
OUTPUT
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
list1.index(700)
ValueError: 700 is not in list
To find out whether an element is present in a list or not, we can do the following:
>>> list1= [100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> 500 in list1
OUTPUT
True
EXPLANATION
So, we see that 'True' was returned as '500' was present in the list list1.
LIST OPERATORS
Python allows to use mathematical operators like +, * etc. to be used with lists. The +
operator is used to add elements to the list and * operator is used to add the complete
list repeatedly towards the end.
EXAMPLE 1
>>> list1=[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> list1 = list1 + [80]
>>> print(list1)
OUTPUT
[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin', 80]
EXAMPLE 2
>>> list2=["Raman", 100, "Ashwin"]
>>> list2=list2*2
>>> print(list2)
OUTPUT
['Raman', 100, 'Ashwin', 'Raman', 100, 'Ashwin']
LIST FUNCTIONS
FUNCTION
EXPLANATION
EXAMPLE
len()
Returns the length of the list
SYNTAX:
len(list-name)
>>> list1=[100, 200, 50, 400, 500, 'Raman', 100, 'Ashwin']
>>> len(list1)
max()
Returns the element with maximum value from the list
NOTE: To use the max() function all values in the list must be of same type
>>> list3=[10,20,30,40]
>>> max(list3)
40
>>> list4=['A', 'a', 'B','C']
>>> max(list4)
'a'
here it will return the alphabet with maximum ASCII value
>>> list5=['ashwin','bharat','shelly']
>>> max(list5)
'shelly'
here it will return the string which starts with character having highest ASCII value.
>>> list5=['ashwin','bharat','shelly', 'surpreet']
>>> max(list5)
'surpreet'
If there are two or more string which start with the same character, then the second
character is compared and so on.
min()
Returns the element with minimum value from the list
NOTE: To use the min() function all values in the list must be of same type
>>> list3=[10,20,30,40]
>>> min(list3)
10
>>> list4=['A', 'a', 'B','C']
>>> min(list4)
'A'
here it will return the alphabet with minimum ASCII value
>>> list5=['ashwin','bharat','shelly']
>>> min(list5)
'ashwin'
here it will return the string which starts with character having smallest ASCII value.
>>> list5=['ashwin','bharat','shelly', 'surpreet']
>>> min(list5)
'ashwin'
If there are two or more string which start with the same character, then the second
character is compared and so on.
count()
It is used to count the occurrences of an item in the list.
>>> list6=[10,20,10,30,10,40,50]
>>> list6.count(10)
Q1. Write a Python script to input a number and count the occurrences of that number in
a given list.
list1=[10, 20,30, 40, 10, 50, 10]
num=eval(input("enter a number"))
count=0
for i in list1:
if num == i:
count=count+1
print(num, "is present", count, "number of times")
OUTPUT
enter a number10
10 is present 3 number of times
enter a number45
45 is present 0 number of times
Q2 Write a Python script to input a number and perform linear search.
list1=[10, 20,30, 40, 10, 50, 10]
num=eval(input("enter a number"))
found = False
position = 0
while position < len(list1) and not found:
if list1[position] == num:
found = True
position = position + 1
if found:
print(num, "is present at position", position-1)
else:
print(num, "is not present")
OUTPUT
enter a number20
20 is present at position 1
enter a number100
100 is not present in girl