You are on page 1of 26

List in Python

->If we want to represent group of object as a single entity, then list is


being used.

-> List can hold multiple values of heterogeneous elements under


single variable

-> List is grow able in nature therefore based on incoming flow of data ,
the size of a list is getting increased or decreased.

-> List is mutable in nature hence values in the list can be modified ,
which means that Python will not create a new list when you make
changes to an element of a list.

-> in List, insertion order is preserved(Ordered collection)

The most basic data structure in Python is the sequence(string, list,


tuples etc). Each element of a sequence is assigned a number - its
position or index. The first index is zero, the second index is one, and so
forth.
Python has six built-in types of sequences, but the most common ones
are lists and tuples, The list is a most versatile data type available in
Python which can be written as a list of comma-separated values
(items) between square brackets.
Important thing about a list is that items in a list need not be of the
same type.
How to create a list?
In Python programming, a list is created by placing all the items
(elements) inside a
square bracket [ ], separated by commas.
It can have any number of items and they may be of different types
(integer, float,string etc.).
Empty List
lt=[]
print (lt)
fruits=list() # by using constructor
output
[]
Creating list with same type

lt=[2,4,5]
lt1=['hello','hi','bye']
lt2=[25.7,35.8,93.2]
print (lt)
print (lt1)
print (lt2)
output:
[2, 4, 5]
['hello', 'hi', 'bye']
[25.7, 35.8, 93.2]

List within list


lt=[[2,4,5],['hello','hi','bye'],25.7,35.8,93.2]
print (lt)

List with different data types


lt=[1,'rahul',18,87.5]
a=[1,"abc",True,5.7,2+3j]
print (lt)
print(a)
Traversing a List: The process of iterating the elements of a list one by
one is called Traversing. We can traverse a list by using in operator
and range function.
List=[1,2,3,4,5]
for i in List:
print(i, end=“ ”)#1 2 3 4 5
>>> for i in List:
print(i)
O/P
1
2
3
4
5

>>>for i in List:
print(i,end="#")

O/P

1#2#3#4#

By using loop:

List=[1,2,3,4,5]
for i in range(0, len(List)):
print(list[i],end=“ “)# 1 2 3 4 5
Access Elements
We can access list elements by using index and slicing.
The index operator [] is used to access an item in a list. Index starts from 0.

lt=[2,4,5]

lt1=['sun','mon','tue']

lt2=[['one','two','three'],[4,5,6]]

print(lt[0])

print(lt1[-2])

print(lt2[0][1])

print(lt2[-1][-1])

print(lt2[0][1])

Using for loop

lt=[2,4,5]

lt2=[['one','two','three'],[4,5,6]]

for i in lt:

print(i)

for i in lt2:

for j in i:

print(j,end="")

print()
Nested List: A list inside another list is called Nested List.

Examples:

>>> L=[1,2,[4,5],7]

>>> print(L)

[1, 2, [4, 5], 7]

>>> L[0]

>>> L[-2]

[4, 5]

>>> L[-2][0]

>>> L[-2][1]

>>> L[-2][-1]

>>> L[-2][0]

>>> L

[1, 2, [4, 5], 7]

>>> L[3]=9

>>> L
[1, 2, [4, 5], 9]

Examples:

X=[1,7,[5,6],10]

Y=list(X)

print(X,Y)

X[2][0]=7

print(X,Y)

X[0]=43

print(X,Y)

Slicing a list: List slices are the sub-parts of a list extracted out. List slices can
be created through the use of indexes. Slicing is used to retrieve a subset of
values.

Syntax: list[start:end:step]

If step is +ve: it prints a list from start to end-1.

 If start is omitted, then by default its value is 0


 If end is omitted, then by default its value is end-1
 If step is omitted, then by default its value is 1.

Examples:

>>> list1=[24,56,10,99,28,90,20,22,34]

>>> slice1=list1[0:6:1]

>>> print(slice1)
[24, 56, 10, 99, 28, 90]

>>> slice2=list1[3:-3]

>>> print(slice2)

[99, 28, 90]

>>> print(list1)

[24, 56, 10, 99, 28, 90, 20, 22, 34]

>>> list1[3]=100

>>> print(list1)

[24, 56, 10, 100, 28, 90, 20, 22, 34]

>>> list1[0:7:3]

[24, 100, 20]

>>> list1[:]

[24, 56, 10, 100, 28, 90, 20, 22, 34]

>>> list1[::]

[24, 56, 10, 100, 28, 90, 20, 22, 34]

If step is –ve:

1. if start is omitted, by default its values is -1.

2. if end is omitted, by default its values is –len(list).

3. if step is omitted, be default its values is 1.

For examples :

>>> list1[-1::]
[34]

>>> list1[::-1]

[34, 22, 20, 90, 28, 100, 10, 56, 24]

>>> list1[:-5:-2]

[34, 20]

>>> L=[10,20,30,40,50]

>>> L[0:len(L):1]

[10, 20, 30, 40, 50]

>>> L[0:]

[10, 20, 30, 40, 50]

>>> L[0:len(L)]

[10, 20, 30, 40, 50]

>>> L[1:5]

[20, 30, 40, 50]

>>> L[1:5:0]

Traceback (most recent call last):

File "<pyshell#5>", line 1, in <module>

L[1:5:0]

ValueError: slice step cannot be zero

>>> L[1:5:2]

[20, 40]
>>> L[::-1]

[50, 40, 30, 20, 10]

>>> L[0:5:-1]

[]

>>> L[-4:-1:-1]

[]

>>> L[-4:-1]

[20, 30, 40]

>>> L[-5:3:1]

[10, 20, 30]

Nested list: if a list containing another list as an element, then it is called


Nested list.

For examples:

Joining a list: multiple sequence(list) can be combined with the help of +


operators which is called list concatenation.
Note: here both the operand must be the list.
For examples:
>>> list1=[1,2,3]
>>> list2=[4,5,6]
>>> list1+list2
[1, 2, 3, 4, 5, 6]
>>> print(list1)
[1, 2, 3]
>>> print(list2)
[4, 5, 6]
If you combine other than list like (string, tuples and Boolean types), you will
get errors. Following statement cause an error
>>> str="abc"
>>>list1+str
>>>list1+(10,20,30)

Replicating/repetition a list: We can create multiple copies of same list by


using * operator. But here one of the argument should be list and another
must be number
Syntax: 1. number * List
2. List * number
Otherwise it causes an error.
For examples:
>>> list1=[2,3,4]
>>> list1*3
[2, 3, 4, 2, 3, 4, 2, 3, 4]
>>> list2=[4,5,6,7,8]
>>> list2*10

Q. Write a program to sum all the elements of the list?


Sol:
sum=0
L=[1,2,3,4,5,7]
for i in L:
sum=sum+i
print("sum of the list is:",sum)

Q. Write a program to take list as input , adds 5 in all the odd values and 10 in
all the even values of the list L. Also display the list
L=[10,20,3,100,65,87,2]
print("old list",L)
for i in range(0,len(L)):
if L[i]%2==0:
L[i]=L[i]+10
else:
L[i]=L[i]+5
print("New list:",L)

Q. WAP to find and display the sum of all the values which are ending with 3
from a list?
Suppose the list is [33,13,92,99,3,12]
L=[33,13,92,99,3,12]
sum=0
x=len(L)
for i in range(0,x):
if L[i]%10==3:
sum=sum+L[i]
print("the sum of the list ",sum)

List function/method:
1. append(): It adds a single item to the end of the list. It doesn’t create a new
list; rather it modifies the original list.
Syntax: list.append(item)
for
examples:
.
>>> list1=[1,2,3,4,5,6]
>>> print(list1)
[1, 2, 3, 4, 5, 6]
>>> id(list1)
37124496
>>> list1.append(7)
>>> print(list1,id(list1))
[1, 2, 3, 4, 5, 6, 7] 37124496
>>> L=[]
>>> L1=[]
>>> L2=[]
>>> print(L,L1,L2)
[] [] []
>>> for i in range(6,10):
L.append(i)

>>> print(L)
[6, 7, 8, 9]
>>> print(L1)
[]
>>> for i in range(10,4,-2):
L1.append(i)

>>> print(L1)
[10, 8, 6]
>>> print(L)
[6, 7, 8, 9]
>>> print(L1)
[10, 8, 6]
>>> L2
[]
>>> for i in range(len(L1)):
L2.append(L[i]+L1[i])

>>> print(L2)
[16, 15, 14]
>>> L2.append(len(L)-len(L1))
>>> L2
[16, 15, 14, 1]

2. extend() method: extends() method adds one list at the end of another list.
In other words, all the items of a list are added at the end of an already
created list.

Syntax: list1.extend(list2) # where list2 are the list which will be extended
For examples:
>>> L1=[100,200,300,400]
>>> L2=[10,20,30]
>>> print(L1,L2]
>>> print(L1,L2)
[100, 200, 300, 400] [10, 20, 30]
>>> L1.extend(L2)
>>> print(L1)
[100, 200, 300, 400, 10, 20, 30]
>>> L1.extend([80,90])
>>> L1
[100, 200, 300, 400, 10, 20, 30, 80, 90]

For example 2:
>>> L1
[100, 200, 300, 400, 10, 20, 30, 80, 90]
>>> print(L1)
[100, 200, 300, 400, 10, 20, 30, 80, 90]
>>> L1.extend([[500,600]])
>>> print(L1)
[100, 200, 300, 400, 10, 20, 30, 80, 90, [500, 600]]
>>> L1.append([700,800])
>>> L1
[100, 200, 300, 400, 10, 20, 30, 80, 90, [500, 600], [700, 800]]

3. insert(): insert() method is used to insert an element/object at a specified


index. This function takes 2 arguments
1. The index where an item/object is to be inserted
2. The element itself.
Syntax: list_name.insert(index_number,value)
Example:
>>> L1=[10,20,"Akash",60]

>>> L1

[10, 20, 'Akash', 60]

>>> L1.insert(1,30)

>>> print(L1)

[10, 30, 20, 'Akash', 60]


>>> L=[1,2,10,12,16]

>>> print(L)

[1, 2, 10, 12, 16]

>>> L[0]

>>> L[-3]

10

>>> L.insert(2,3)

>>> print(L)

[1, 2, 3, 10, 12, 16]

>>> L.insert(4,11)

>>> L

[1, 2, 3, 10, 11, 12, 16]

>>> L.insert(0,0)

>>> L

[0, 1, 2, 3, 10, 11, 12, 16]


Homework

For examples:
1.
List1=[10,15,20,25,30]
List1.insert(3,4)
List1.insert(2,3)
print(List1[-5])
(i) 2 (ii)3 (c) 4 (d) 20

x=[[10.0,11.0,12.0],[13.0,14.0,15.0]]
y=x[1][2]
print(y) #15.0
print(x[-2][1])#11.0

Delete Operations:
Python provides operator for deleting/removing an item from a list. There are
many methods for deletions.

pop(): It removes the elements from the specified index and also returns the
element which was removed. pop() removes last element if the index is not
specified.
Syntax: List.pop(index)
Examples:
>>> L1=[1,2,5,4,70,10,90,80,50]
>>> a=L1.pop(1)
>>> a
2
>>> L1
[1, 5, 4, 70, 10, 90, 80, 50]
>>> print(L1.pop(-2))
80
>>> L1
[1, 5, 4, 70, 10, 90, 50]
>>> L1.pop()
50
>>> L1
[1, 5, 4, 70, 10, 90]
>>> L1.pop()
90
>>> L1
[1, 5, 4, 70, 10]
>>> L1=[1,2,5,4,70,10,90,80,50]
>>> L1.pop(3)
4
>>> L1
[1, 2, 5, 70, 10, 90, 80, 50]
>>> L1.pop()
50
>>> L1
[1, 2, 5, 70, 10, 90, 80]
>>> L1.pop(-2)
90
>>> L1
[1, 2, 5, 70, 10, 80]
Note: If you don’t pass any index, then pop() method removes last element
from the list.
del statement:
del statement removes the specified element from the list but not return the
deleted values. del statement also destroy whole list object.
>>> L1=[100,200,300,400,500]
>>> print(L1)
[100, 200, 300, 400, 500]
>>> del L1[3]
>>> print(L1)
[100, 200, 300, 500]
>>> del(L1[1:3])
>>> print(L1)
[100, 500]

remove(): remove() function is used when we know the element to be


deleted, not the index of the element.
Syntax:
list.remove(<element>)
Examples:
L1=[1,2,5,4,70,10,90,80,50]
>>>L1.remove(80)
>>> L1
[1, 2, 5, 4, 70, 10, 90, 50]
>>> L1.remove(4)
>>> print(L1)
[1, 2, 5, 70, 10, 90, 50]
4.reverse(): The reverse() function in Python reverses the order of the
elements in a list. This function reverses the item of the list.
>>> list1=[24,56,10,99,28,90]
>>> list1.reverse()
>>> list1
[90, 28, 99, 10, 56, 24]
It replaces a new value “in place” of an item that already exists in the list i.e. it
doesn’t create a new list.

sort() method: This function sorts the item of the list, by default in
ascending/increasing order.
>>> L2=[10,4,20,98,2,100]
>>> L2.sort()
>>> L2
[2, 4, 10, 20, 98, 100]
# in descending order
>>> L3=[10,4,20,98,2,100]
>>> L3.sort(reverse=True)
>>> L3
[100, 98, 20, 10, 4, 2]
Example:
>>> L=[1,9,2,3,7,5]
>>> L.sort()
>>> L
[1, 2, 3, 5, 7, 9]
>>> L1=["Bob","Aman","Chetan","Ashish","Debasis"]
>>> L1.sort()
>>> L1
['Aman', 'Ashish', 'Bob', 'Chetan', 'Debasis']
>>> L.sort(reverse=True)
>>> L
[9, 7, 5, 3, 2, 1]
>>> L1.sort(reverse=True)
>>> L1
['Debasis', 'Chetan', 'Bob', 'Ashish', 'Aman']

clear() method: The clear() method removes all the items from the list. This
method doesn’t take any parameters. The clear() method only empties the
given list.
>>> L1=[10,20,30,40]
>>> print(L1)
[10, 20, 30, 40]
>>> L1.clear()
>>> print(L1)
[]
Homework
Q. Write the most appropriate list method to perform the following task:
(i) Delete a given element from the list
Sol: remove()

(ii) Delete the 3rd element from the list.


Sol: pop(3)
(iii)Add elements in the list at the end of the list.
Sol: extend()
(iv) Add an element in the beginning of the list.
Sol: insert()
(v) Add single element at the end of the list.
Sol: append()
Updating a list:
List are mutable; You can assign new value to existing values. We can use
assignment operator(=) to change an item or a range of items.

>>> L2=[1,2,3]
>>> L2[1]=4
>>> L2
[1, 4, 3]

count() method: count() method counts how many times an element has occurred in a list
and returns it.
Syntax: list.count(element)
For examples:
>>> L=[10,20,30,40,50]
>>> L.count(10)
1
>>> L.extend([10,70,90])
>>> L
[10, 20, 30, 40, 50, 10, 70, 90]
>>> L.count(10)
2

index(): List can easily be searched for values using the index() method that expects a
value that is to be searched.
List_name.index(element)

>>> list=[100,200,50,400]
>>> list.index(200)
1
>>> list.index(500)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
list.index(500)
ValueError: 500 is not in l
Q.1 Write a program to create a list and perform following operation
For examples: if the list is: [1,45,22,3,20]
The output should be
The sum of even: 42
The odd is : 49
Answer:
L=[1,45,22,3,20]
length=len(L)
soe,sod=0,0
for i in range(length):
if L[i]%2==0:
soe=soe+L[i]
else:
sod=sod+L[i]
print("sum of even",soe)
print("sum od odd",sod)

max(): Returns the element with the maximum values from the list.
Syntax: max(<list>)
Examples:
L=[10,2,3,1,5,10,7,8,20,10]
print(max(L))
>>> L=['Ajay','suman','Raj','aman','Bob']
>>> max(L)
'suman'
Note: max(), min(), sum() never work for mixed type list.
min(): Returns the element with the minimum values from the list.
>>> L=['Ajay','suman','Raj','aman','Bob']
>>> min(L)#’Ajay’

sum(): Returns the addition of all elements of the list.


>>> L=[10,20,30,60,70]
>>> sum(L)
190

Homework

1. What is the output of following code ? [CBSE Board 2021 ]


L1,L2=[10,15,20,25],[]
for i in range(len(L1)):
L2.insert(i,L1.pop())
print(L1,L2,sep=”&”)

2. What is the output of the following code ? [CBSE Board Exam 2021]
L=[]
for i in range(4):
L.append(2*i+1)
print(L[::-1])

3. What is the output of following code ? [CBSE Board 2021 ]


L1,L2=[10,15,20,25],[]
for i in range(len(L1)):
L2.insert(i,L1.pop())
print(L1,L2,sep=”&”)
4. What is the output of the following code ? [CBSE Board Exam 2021]
L=[]
for i in range(4):
L.append(2*i+1)
print(L[::-1])

Q. 5 Which of the following can add an element at any index in the list?
i. insert( ) ii. append( ) iii. extend() iv. all of these
6.What will be the output of the following code:
>>>l1=[1,2,3]
>>>l1.append([5,6])
>>>l1
i. [1,2,3,5,6] ii. [1,2,3,[5,6]] iii. [[5,6]] iv. [1,2,3,[5,6]]

7.What will be the output of the following code:


>>>l1=[1,2,3]
>>>l2=[5,6]
>>>l1.extend(l2)
>>>l1
8. [5,6,1,2,3] ii. [1,2,3,5,6] iii. [1,3,5] iv. [1,2,3,6]
5.What will be the output of the following code:
>>>l1=[1,2,3]
>>>l1.insert(2,25)
>>>l1
9. [1,2,3,25] ii. [1,25,2,3] iii. [1,2,25,3] iv. [25,1,2,3,6]
10.
>>>l1=[10,20,30,40,50,60,10,20,10]
>>>l1.count(‘10’)
i. 3 ii. 0 iii. 2 iv. 9
11.Which operators can be used with list?
i. in ii. not in iii. both (i)&(ii) iv. Arithmetic operator only
12.Which of the following function will return the first occurrence of the specified element
in a list.
i. sort() ii. value() iii. index() iv. sorted()

sorted():Python sorted() function returns a sorted list from the iterable object.
Syntax: sorted(iterable, key, reverse)
Example:
L=[4,5,1,2,7,6]
>>> print(sorted(L))
[1, 2, 4, 5, 6, 7]
>>> print(sorted(L,reverse=True))
[7, 6, 5, 4, 2, 1]

copy(): copy makes a copy of the list is to assign it to


another list. copy() generates different id for different
list.
>>> L=[10,20,30,40]
>>> L1=L.copy()
>>> L
[10, 20, 30, 40]
>>> L1
[10, 20, 30, 40]
>>> id(L1)
38655880]
>>> id(L)
38583232
>>> L=[10,20,30,40]
>>> L1=L.copy()
>>> L
[10, 20, 30, 40]
>>> L1
[10, 20, 30, 40]
>>> id(L1)
38655880]
>>> id(L)
38583232
Prescription
Dear students,
(1) try to solve and run above homework program on your system .
Apart from that
(2) Try, run and understand those problems given in 7.46-7.47 page of Preeti Arora
book.
(3) run Question No. 7 and 8 of unsolved Questions given in 7.53 page of Preeti Arora
book.

You might also like