CHAPTER-09
LISTS
INTRODUCTION TO LIST:
1. The data type list is an ordered sequence which is mutable and made up of one or
more elements.
2. A list can have elements of different data types, such as integer, float, string, tuple
or even another list.
3. Elements of a list are enclosed in square brackets and are separated by comma.
4. Like string indices, list indices also start from 0.
5. EXAMPLE:
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]
6. >>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello']
Accessing Elements in a List:
1. The elements of a list are accessed in the same way as characters are accessed in a
string.
2. >>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
2
3. >>> list1[3] #return fourth element of list1
8
4. >>> list1[15]
IndexError: list index out of range #an expression resulting in an integer index
5. >>> list1[1+4]
12
6. >>> list1[-1] #return first element from right
12
7. >>> n = len(list1)
>>> print(n)
6
8. #return the last element of the list1
>>> list1[n-1]
12
9. #return the first element of list1
>>> list1[-n]
2
Lists are Mutable:
In Python, lists are mutable. It means that the contents of the list can be changed
after it has been created.
>>> list1 = ['Red','Green','Blue','Orange']
>>> list1[3] = 'Black'
>>> list1 #print the modified list
list1 ['Red', 'Green', 'Blue', 'Black']
LIST OPERATIONS:
1. Concatenation:
1. Python allows us to join two or more lists using concatenation operator
depicted by the symbol +.
>>> list1 = [1,3,5,7,9]
>>> list2 = [2,4,6,8,10]
>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
2. The concatenation operator '+’ requires that the operands should be of list type
only. If we try to concatenate a list with elements of some other data type,
TypeError occurs.
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1 TypeError: can only concatenate list
[Link]:
1. Python allows us to replicate a list using repetition operator depicted by symbol *.
>>> list1 = ['Hello']
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
3. Membership:
1. The membership operators in checks if the element is present in the list and
returns True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'orange' in list1
False
2. The not in operator returns True if the element is not present in the list, else it
returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'orange' not in list1
True
>>> 'Green' not in list1
False
4. Slicing:
1. The slicing operation can also be applied to lists.
>>> list1 =['Red','Green','Blue','orange', 'Magenta','Yellow','Black']
1. >>> list1[2:6]
['Blue', 'orange', 'Magenta', 'Yellow']
2. >>> list1[2:20]
['Blue', 'orange', 'Magenta', 'Yellow', 'Black']
3. >>> list1[7:2] #first index > second index #results in an empty list
[]
4. >>> list1[:5] #first index missing
['Red','Green','Blue','orange','Magenta']
5. >>> list1[0:6:3]
['Red','Blue','Magenta']
6. #elements at index -6,-5,-4,-3 are sliced
>>> list1[-6:-2]
['Green','Blue','orange','Magenta']
7. >>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black']
8. #whole list in the reverse order
>>> list1[::-1]
['Black','Yellow','Magenta','orange','Blue', 'Green','Red']
TRAVERSING A LIST:
We can access each element of the list or traverse a list using a for loop or a while loop.
(A) List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
Another way of accessing the elements of the list is using range() and len() functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black
(B) List Traversal Using while Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> i = 0
>>> while i < len(list1):
print(list1[i])
i += 1
Output:
Red
Green
Blue
Yellow
Black
LIST METHODS AND BUILT-IN FUNCTIONS:
Method Description Example
len() Returns the length of the list >>> list1 = [10,20,30,40,50]
passed as the argument >>> len(list1)
5
list() Creates an empty list >>> list1 = list()
if no argument is >>> list1
passed. []
Creates a list if a >>> str1 = 'aeiou'
sequence is passed as >>> list1 = list(str1)
an argument >>> list1
['a', 'e', 'i', 'o', 'u']
append() Appends a single element >>> list1 = [10,20,30,40]
passed as an argument at >>> [Link](50)
the end of the list >>> list1
[10, 20, 30, 40, 50]
extend() Appends each element of >>> list1 = [10,20,30]
the list passed as argument >>> list2 = [40,50]
to the end of the given list >>> [Link](list2)
>>> list1 [10, 20, 30, 40, 50]
insert() Inserts an element at a >>> list1 = [10,20,30,40,50]
particular index in the list >>> [Link](2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
count() Returns the number of times >>> list1 = [10,20,30,10,40,10]
a given element appears in >>> [Link](10)
the list 3
index() Returns index of the first >>> list1 = [10,20,30,20,40,10]
occurrence of the element in >>> [Link](20)
the list. If the element is not 1
present, >>> [Link](90)
ValueError is generated ValueError: 90 is not in list
remove() Removes the given >>> list1 = [10,20,30,40,50,30]
element from the list. >>> [Link](30)
If the element is >>> list1
present multiple [10, 20, 40, 50, 30]
times, only the first
occurrence is
removed.
If the element is not
present, then
ValueError is
generated
pop() Returns the element >>> list1 = [10,20,30,40,50,60]
whose index is passed >>> [Link](3)
as parameter to this 40
function and also >>> list1
removes it from the [10, 20, 30, 50, 60]
list.
If no parameter is
given, then it returns
and removes the last
element of the list
reverse() Reverses the order of >>> list1 = [34,66,12,89,28,99]
elements in the given list >>> [Link]()
>>> list1
[ 99, 28, 89, 12, 66, 34]
sort() Sorts the elements of the >>>list1 = ['Tiger','Zebra','Lion', 'Cat',
given list 'Elephant' ,'Dog']
>>> [Link]()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger',
'Zebra']
sorted() It takes a list as parameter >>> list1 = [23,45,11,67,85,56]
and creates a new list >>> list2 = sorted(list1)
consisting of the same >>> list1
elements arranged in sorted [23, 45, 11, 67, 85, 56]
order >>> list2
[11, 23, 45, 56, 67, 85]
min() Returns minimum or >>> list1 = [34,12,63,39,92,44]
smallest element of >>> min(list1)
the list 12
max() Returns maximum or >>> max(list1)
largest element of the 92
list >>> sum(list1)
sum() Returns sum of the 284
elements of the list
NESTED LISTS:
1) When a list appears as an element of another list, it is called a nested list.
>>> list1 = [1,2,'a','c',[6,7,8],4,9]
>>> list1[4]
[6, 7, 8]
2) To access the element of the nested list of list1, we have to specify two indices
list1[i][j].
3) The first index i will take us to the desired nested list and second index j will take
us to the desired element in
that nested list.
>>> list1[4][1]
7
COPYING LISTS:
1) The simplest way to make a copy of the list is to assign it to another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
2) The statement list2 = list1 does not create a new list.
3) It just makes list1 and list2 refer to the same list object.
4) Any changes made to either of them will be reflected in the other list.
>>> [Link](10)
list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10]
We can also create a copy or clone of the list as a distinct object by three methods.
The first method uses slicing
The second method uses built-in function list()
The third method uses copy() function of python library copy.
Method 1
We can slice our original list and store it into a new variable as follows:
newList = oldList[:]
Example:
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
Method 2
We can use the built-in function list() as follows:
newList = list(oldList)
Example: >>> list1 = [10,20,30,40]
>>> list2 = list(list1)
>>> list2
[10, 20, 30, 40]
Method 3
We can use the copy () function as follows:
import copy
newList = [Link](oldList)
Example:
>>> import copy
>>> list1 = [1,2,3,4,5]
>>> list2 = [Link](list1)
>>> list2
[1, 2, 3, 4, 5]
LIST AS ARGUMENT TO A FUNCTION:
Whenever a list is passed as an argument to a function, we have to consider two
scenarios:
(A) Elements of the original list may be changed, i.e. changes made to the list in the
function are reflected back in the calling function.
def mlist(num):
[Link](6)
num[0]=10
list=[1,2,3,4,5]
mlist(list)
print(“Modified_list:”, list)
(B) If the list is assigned a new value inside the function then a new list object is created
and it becomes the local copy of the function. Any changes made inside the local copy of
the function are not reflected back to the calling function.
def new_list(num):
num=[10,20,30]
[Link](40)
print("Inside the fucntion", num)
my_list=[1,2,3,4,5]
new_list(my_list)
print("The original list after function call", my_list)
LIST MANIPULATION:
1. Write a program to find the number of times an element occurs in the list.
list=eval(input(“Enter the elements”))
num=int(input(“ Enter the element to check”)
if num in list:
print(num,”is present”,in [Link](num),”number of times”)
else:
print(num,” is not present in list”)
2. Write a function that returns the largest element of the list passed as parameter.
def largest(list):
largest = max(list)
return largest
l=eval(input(“enter the element”)
print(“The largest element in the given list is”,largest(l))
3. Write a program to read a list of elements. Modify this list so that it does not
contain any duplicate elements, i.e., all elements occurring multiple times in the
list should appear only once.
list=eval(input(“Enter the list:”))
list1=[ ]
for i in list:
if i not in list1:
[Link](i)
print(“List without duplicate elements”, list1)