0% found this document useful (0 votes)
25 views111 pages

Python Lists: Creation, Access, and Operations

Uploaded by

Saksham Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views111 pages

Python Lists: Creation, Access, and Operations

Uploaded by

Saksham Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

Chapter 5

LISTS

AISMV---XI---IP---POOJA THAKUR
List data type

Creating Lists

Accessing List elements

Learning Lists as Mutable data type


Objective
Concatenation in Lists

Replication in Lists

Membership Operators in Lists

Slicing in Lists

AISMV---XI---IP---POOJA THAKUR
Sequences in Python
➢Strings ex: “123”
➢Lists ex: [1,2,3]
➢Tuples ex: (1,2,3)
➢Dictionaries ex{‘a’:1, ‘b’:2, ‘c’:3}

AISMV---XI---IP---POOJA THAKUR
LISTS
List is a collection of values or an ordered
sequence of values and items.
The items in a list can be of any type: strings,
integers, float or even list.

List elements are enclosed in [ ]

Lists are mutable i.e. values in the list can be


modified

Lists can have heterogeneous data types.

AISMV---XI---IP---POOJA THAKUR
LIST
• A M O S T V ER S ATI LE D ATA TY P E I N P Y TH O N.

• A LI S T O F C O M MA S EPA R ATED VA LU ES ( I TEM S) BETW EEN

S Q U A R E BR A C K ETS [ ] .

• I TEM S N EED N O T TO BE O F S A M E TY P E. ( U N LI KE

S TR I N G S)

• LI S TS A R E M U TA BLE. ( U N LI KE S TR I N G S)

EX - LIST1 = [ ‘ SAKET’, ‘NOIDA’, ‘GURGAON’ , ‘MV’]


LIST2 = [20 , 30 , ‘C++’, 50 , ‘PYTHON’]
LIST3 = [1990 , 20.05 , [ ‘ PHY’ , ‘ENG’ ] , 2006 ]

AISMV---XI---IP---POOJA THAKUR
CREATING LISTS
To Create a list, you separate the elements with a comma and enclose them with a bracket [ ].

The Syntax is :
<name of list>=[<value>,<value>,value>]
For example:
>>> list1=[67,82,98,78,87] # a numeric list
>>> list 2=[‘pen’, ’pencil’, ’scale’, ’eraser’, ‘marker’] # a character/string list
>>> list3=[‘A V Raman’, 35, ‘Scientist’ , 87650.00] # a list with multiple type values
>>> list 4=[] # an empty list
>>>list5=[1,2,[10,20,30],4,5] # Nested list

AISMV---XI---IP---POOJA THAKUR
CREATING LISTS
Creating list from existing sequence using list()
The Syntax is :
<name of list>=list(sequence/string)
For example:
>>> list1=list(‘computer’) # convert a string to list
>>> list 1
[‘c’ , ‘o’ , ‘m’ , ‘p, ‘u’ , ‘t’ , ‘e’ , ‘r’ ]
>>> list2=list() # create an empty list
>>>list3=[10,20,30,40,50]
>>>list4=list3
>>>list4 output-> [10,20,30,40,50]

AISMV---XI---IP---POOJA THAKUR
Accessing List Elements
➢We can access individual list elements using indexing and a range of elements using slicing.
➢Python indexes the list elements from left to right (forward indexing), the first element has an
index 0, in backward indexing, the indexing starts from -1 (right to left)
➢Individual elements in a list can be accessed by specifying the list name followed by a number
in square brackets [].

FORWARD INDEXING

BACKWARD INDEXING
AISMV---XI---IP---POOJA THAKUR
Accessing List Elements
Each element in the list can be accessed using index.
Syntax:
<listname>[<index>]
Example: Consider the list L1
L1=[1,2,3,4,5,6,7,8,9,10]
L1[0] → return 1
L1[2+1] → return 4 #access the 3rd index element
L1[9-2] → return 8 # access the 7th index element
L1[-2] → return 9

AISMV---XI---IP---POOJA THAKUR
Lists are mutable
➢When the bracket operator appears on the left side of an
assignment, a value is assigned to the element of a list .

numbers = [24 , 35 , 78]


numbers[1] = 56
print (numbers)
[24 , 56 , 78]
L=[1,2,3]
L[1:3] = 5,6
Print (L)
would print [1,5,6]

Note: A list is a relationship between indices and elements. This relationship is called
Mapping. Each index “maps to” one of the elements.

AISMV---XI---IP---POOJA THAKUR
Lists are Mutable

>>> basket = ['bread', 'butter', 'milk']


>>> basket[0] = 'cake'
>>> basket
>>> basket[-1] = 'water'
>>> basket

Output:

['cake', 'butter', 'milk’]


['cake', 'butter', 'water']

AISMV---XI---IP---POOJA THAKUR
 len(list)

3
L=[1,2,3]
print(len(L))
 + (concatenation)
Basic List
Operations L=[1,2,3]
L2=[3,4,5]
and Functions [1, 2, 3, 3, 4, 5]
print(L+L2)

 * (repetition)
L=[1,2,3]
print(L*3) [1, 2, 3, 1, 2, 3, 1, 2, 3]

AISMV---XI---IP---POOJA THAKUR
len()
➢len() returns the length of the list or the count of the
elements in a list.
➢Example:
numbers = [24 , 35 , 78]
len(numbers) # return 3
L=[“riya”,”adit”, “siya”, “rajat”, “Aditya”]
len(L) ?

Note: len() returns an integer type of value

AISMV---XI---IP---POOJA THAKUR
Concatenation

L=[“Aditya”, “Rajat”]
L1=[“Divya”, “Shivam”]
Print(L+L1) # Return ['Aditya', 'Rajat', 'Divya', 'Shivam']
L2= [1,2,3]
L3=L1+L2 # Return ['Divya', 'Shivam', 1, 2, 3]
L2+”Hello” # return TypeError: can only concatenate list (not "str") to list

L2+2 # return TypeError: can only concatenate list (not "int") to list

AISMV---XI---IP---POOJA THAKUR
Replication

TypeError: can't multiply sequence by non-int of


type 'list'

L=[“Aditya”, “Rajat”]

Print(L*2) # Return ['Aditya', 'Rajat', 'Aditya', 'Rajat']

L2= [1,2,3]

L3=L2*4 # Return [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

L2 *”Hello” # Return TypeError: can't multiply sequence by non-int of type 'str'

AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
Consider the list1 and list2 given below:
list1=[67,82,98,92,78,87]

print(list1[-4:]) [98,92,78,87] Prints the last 4 elements


print(list1[3:] [92,78,87] Prints from 3rd index till end of list

list2=[‘pen’ ,’pencil’, ’rubber’, ’scale’, ’eraser’, ’marker’]

Print(list[-3:] [‘scale’, ‘eraser’ , ‘marker’]

print(list2[2:5]) [‘rubber’, ‘scale’, ‘eraser’]


Print(list2[10]) Index error
Note: If you read or write an element that does not exist, IndexError message will appear on
the screen
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
Slicing operations allow us to create new list by taking out elements from an
existing list
◦ Syntax:

<listname>[start:stop:step]

0 1 2 3 4
Red Yellow Blue Green white

-5 -4 -3 -2 -1
List1=["red","yellow","blue","green","white"]
List1[2:6] ['blue', 'green', 'white']
List1[2:20]
['blue', 'green', 'white']
List1[5:2]
[] Empty list
List1[:5]
[‘red’, ‘yellow’,‘blue', 'green', 'white']

AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4
Red Yellow Blue Green white

-5 -4 -3 -2 -1

List1[0:4:2] [‘red', ‘blue’]


List1[-5:-2] [‘red', ‘yellow’, ‘blue’]
List1[::2] [[‘red', ‘blue', 'white']
List1[::-1] ['white', 'green', 'blue', 'yellow', 'red']

AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4 5 6 7 8 9

L= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

print(l[-7::-2])

print(l[::-2]) #every second element from right to left

print(l[9:0:-2])

Output:

[2,8,20,18]
[18, 20, 8, 2, 5]
[18, 20, 8, 2, 5]

AISMV------COMPUTER SCIENCE -------DEEPSHIKHA SETHI


Slicing List Elements
0 1 2 3 4 5 6 7 8 9

l= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

print(l[-9:-3]) #since step is positive it moves from l to r

print(l[-len(l):-1:2])

print(l[4:-2]) #4th index to -2th index

Output:

[2,8,20,18]
[18, 20, 8, 2, 5]
[18, 20, 8, 2, 5]

AISMV------COMPUTER SCIENCE -------DEEPSHIKHA SETHI


ITERATING / TRAVERSING THROUGH LIST

Each element of a list can be accessed sequentially using :


for loop
Syntax:
for <item> in <list>:
process each item here
Output:

10
20
30
40
50
60
ITERATING / TRAVERSING THROUGH LIST

Write a program to print the elements of the list L.

Remember!!
else of for loop is only
executed after successful
Output
completion of the loop
ITERATING / TRAVERSING THROUGH LIST

Write a program to print the elements of the list L using len() and range()

Note that i will have the index value so in


order to access the element we need to use
the []

The range() will iterate


from o to n-1
Output i.e. length-1 times
ITERATING / TRAVERSING THROUGH LIST
Program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in reverse order

L=['q','w','e','r','t','y']
length=len(L)
print("The reverse of the list is: ",end=" ")
for a in range(-1,-length-1,-1):
print(L[a],end=" ")

Output:
The reverse of the list is: y t r e w q
ITERATING / TRAVERSING THROUGH LIST
Program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in separate
lines along with element’s both indexes (positive & negative)

L=['q','w','e','r','t','y']
length=len(L)
for a in range(length):
print("At indexes", a, "and" , (a-length), "element:", L[a])
Output:
At indexes 0 and -6 element: q
At indexes 1 and -5 element: w
At indexes 2 and -4 element: e
At indexes 3 and -3 element: r
At indexes 4 and -2 element: t
At indexes 5 and -1 element: y
Which of the following commands will create
a list?
a) list1 = list()
b) list1 = []
c) list1 = list([1, 2, 3])
d) all of the mentioned
Recap
What is the output when we execute
list(“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]

AISMV---XI---IP---POOJA THAKUR
Suppose list1 is [2445,133,12454,123], what
is list1[:1]?
a) 2445
b) 133
c) 12454
Recap d) 123
What is the output when we execute
l=list(“hello”). print(l[::-1)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]

AISMV---XI---IP---POOJA THAKUR
Difference between l=[‘hello’] and
Recap l=[‘h’,’e’,’l’,’l’,’o’]

AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
Consider the list1 and list2 given below:
list1=[67,82,98,92,78,87]

print(list1[-4:]) [98,92,78,87] Prints the last 4 elements


print(list1[3:] [92,78,87] Prints from 3rd index till end of list

list2=[‘pen’ ,’pencil’, ’rubber’, ’scale’, ’eraser’, ’marker’]

Print(list[-3:] [‘scale’, ‘eraser’ , ‘marker’]

print(list2[2:5]) [‘rubber’, ‘scale’, ‘eraser’]


Print(list2[10]) Index error
Note: If you read or write an element that does not exist, IndexError
message will appear on the screen
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
Slicing operations allow us to create new list by taking out elements from an
existing list
◦ Syntax:

<listname>[start:stop:step]

0 1 2 3 4
Red Yellow Blue Green white

-5 -4 -3 -2 -1

List1=["red","yellow","blue","green","white"]
List1[2:6] ['blue', 'green', 'white']
List1[2:20] ['blue', 'green', 'white']
List1[5:2] [] Empty list
List1[:5]
[‘red’, ‘yellow’,‘blue', 'green', 'white']

AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4
Red Yellow Blue Green white

-5 -4 -3 -2 -1

List1[0:4:2] [‘red', ‘blue’]


List1[-5:-2] [‘red', ‘yellow’, ‘blue’]
List1[::2] [[‘red', ‘blue', 'white']
List1[::-1] ['white', 'green', 'blue', 'yellow', 'red']

AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4 5 6 7 8 9

L= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

print(l[-7::-2])

print(l[::-2]) #every second element from right to left

print(l[9:0:-2])

Output:

[2,5]
[18, 20, 8, 2, 5]
[18, 20, 8, 2, 5]

AISMV------COMPUTER SCIENCE -------DEEPSHIKHA SETHI


Slicing List Elements
0 1 2 3 4 5 6 7 8 9

l= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

print(l[-9:-3]) #since step is positive it moves from l to r

print(l[-len(l):-1:2])

print(l[4:-2]) #4th index to -2th index

AISMV------COMPUTER SCIENCE -------DEEPSHIKHA SETHI


Learning Objectives
❖Iterating over a list
❖Nested Lists
❖Comparing Lists
ITERATING / TRAVERSING THROUGH LIST

Each element of a list can be accessed sequentially using :


for loop
Syntax:
for <item> in <list>:
process each item here
Output:

10
20
30
40
50
60
ITERATING / TRAVERSING THROUGH LIST

Write a program to print the elements of the list L.

Remember!!
else of for loop is only
executed after successful
Output
completion of the loop
ITERATING / TRAVERSING THROUGH LIST

Write a program to print the elements of the list L using len() and range()

Note that i will have the index value so in


order to access the element we need to use
the []

The range() will iterate


from o to n-1
Output i.e. length-1 times
ITERATING / TRAVERSING THROUGH LIST
Program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in reverse order

L=['q','w','e','r','t','y']
length=len(L)
print("The reverse of the list is: ",end=" ")
for a in range(-1,-length-1,-1):
print(L[a],end=" ")

Output:
The reverse of the list is: y t r e w q
ITERATING / TRAVERSING THROUGH LIST
Program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in separate
lines along with element’s both indexes (positive & negative)

L=['q','w','e','r','t','y']
length=len(L)
for a in range(length):
print("At indexes", a, "and" , (a-length), "element:", L[a])
Output:
At indexes 0 and -6 element: q
At indexes 1 and -5 element: w
At indexes 2 and -4 element: e
At indexes 3 and -3 element: r
At indexes 4 and -2 element: t
At indexes 5 and -1 element: y
Write a program to display every
alternate element from the list L
given below:

Practice
Question L=[10,20,30,40,50,60,70,80,90,100]

L=[10,20,30,40,50,60,70,80,90,100]
l=len(L)
for i in range(0,l,2):
print(L[i])
A nested list is created by placing a comma-separated
sequence of sublists.

L = ['a', bb’,[ 'cc', 'dd’,[ 'ee', 'ff’]], 'g', 'h']

Nested lists
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h’]

print(L[2]) # Prints ['cc', 'dd', ['eee', 'fff’]]


Nested LIsts
print(L[2][2]) # Prints ['eee', 'fff’]

print(L[2][2][0]) # Prints eee


Negative
Indexing in
Nested lists
Nested List
When a list is contained in another list as a member element, it is a nested list.
Example:
0 1 2 3 4 5 6 7
L=['These','are’, 'a’, ['few','words'],'that','we','will','use’]
-8 -7 -6 -5 -4 -3 -2 -1
0 1
L[3:4]
['few’, 'words'],
0 1 2 0 1 2 3 4
L[3:4][0]

L[3:4][0][1]

L[3:4][0][1][2]
Nested List
Example:

0 1 2 3 4 5 6 7
L=['These','are’, 'a’, ['few','words'],'that','we','will','use’]
-8 -7 -6 -5 -4 -3 -2 -1

“few” in L False

“few” in L[3] True


[L[1]]+L[3]
L[4:]
L[0::2]
What gets printed?
names=[‘Hasan’, ‘Balwant’ , ‘Siya’, ‘Dia’]
print(names[-1][-1])

Recap A) H
B) n
C) a
D)Dia
COMPARING LIST
Python gives the final result of non equality comparisons as soon as it gets a result in
terms of True/False. If corresponding elements are equal it goes on to next element,
and so on until it finds elements that differ.

Consider the lists given below :


COMPARING LIST
We can compare 2 lists using standard comparison operators of Python:
i.e. >,<,>=,<=,==,!=

Consider the lists given below :

True
False
False
True
TypeError: '>=' not supported between instances of 'list' and 'int'

False
MAKING TRUE COPY OF LIST

L1=[1,2,3,4,5]
L2=L1 # both L1 and L2 are pointing to the same memory location
L2[0]=15
print(L1) # The first element at 0 index will be now 15 in both the lists L1 and L2

To make an independent copy we need to create a true copy

We can create a true copy of the list by any of the following methods:

1) By using list() L2=list(L1)

2) By using copy() L2=L1.copy()

3) By using list slice : L2=L1[:]


Making True Copy of List
Write a program to create a copy of the list. In the copy created, add
10 to its first and last element. Display both the lists.
L1=[17,24,15,30,34,27]

L2=L1.copy()
L2[0]+=10
L2[-1]+=10
print(L1)
print(L2)
MAKING DEEP COPY OF LIST

L=['These','are','a',['few','words'],'that','we','will','use’]
L2=L.copy()
L[3][0]=10

L2

from copy import deepcopy


L3=deepcopy(L)

L3[3][0]="new"

L3

L
Lists and strings are interchangeable

We can change lists to string or vice versa by using list() and str() function and hence respective functions can
be used.
>>>L1=list(“hello”) # string to list
>>>L1
[‘h’, ’e’, ‘l’, ‘l’, ‘o’ ]
>>>t=(‘w’, ’e’, ’r’, ’t’, ’y’) # Tuple to list
>>>L2=list(t)
>>>L2
[ ‘w’, ’e’, ’r’, ’t’, ’y’ ]
>>> S=str(L1) # Lists to string
What is the output of the following python code?
l=[None]*10
print(len(l))

Recap A) 10
B)0
C) None
D) Syntax error
List Functions

len() Index() append() extend() insert()

pop() remove() clear() count() sort()

min() max() sum()


len()
The len() returns the length of the list. i.e. number of elements in the list
Syntax:
len(<list>)

L=[1,2,3,None]

Print(len(L)) ?
index()
This function returns the index of first matched item from the list
Syntax:
List.index(<item>)
Example:
Num=[23,54,34,44,35,66,27,88,69,54]
Num.index(54) # return 1

Num.index(10) # value error : 10 is not in list


append()
The append() method adds an item to the end of the list.
Syntax:
List.append(<item>) # it takes exactly one element and returns no value
Example:
Num=[23,54,34,44,35,66,27,88,69,54]
Num.append(55) # adds 55 to the end of the list, it modifies the existing list
print(Num)
Num.append([55,10])

Num.append(55,10)
append()
append() is equivalent to a[len(a):] = [x].
Example 1
l=[4]
l.append(5) Output:
print(l)
[4, 5]
[4, 5, [6]]
l.append([6])
[4, 5, [6], (4, 5)]
print(l)
l.append((4,5))
print(l)
extend()
The extend() method is used for adding multiple elements (given in the form of a list) to a list.
Syntax:
List.extend(<list>) # takes exactly one element (a list type) and returns no value
Example:
L1=[1,2,3]
L2=[4,5]
L1.extend(L2)
print(L1)
print(L2)
L3=L1.extend(L2) # L3 will return None as extend() does not return anything
print(L3)
List Methods
(extend)
list.extend(iterable) -Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] =iterable.
Example 1:
L=[1,2]
L.extend([3,4])
print(L)
L.extend(‘bye’) Output:
print(L) [1, 2, 3, 4]
L.extend((9,10)) [1, 2, 3, 4, 'b', 'y', 'e']
print(L) [1, 2, 3, 4, 'b', 'y', 'e', 9, 10]
L.extend(4) Error
print(L)
Append() Extend()
Append adds one element Extend adds a sequence to
to the list the list
Difference Element can be simple or Element has to be
between sequential data type sequence only
extend and Element will be added as a Element will be split into
single element each individual item
append
Eg Eg
L=[1] L=[1]
L.append([3,4]) L.extend([3,4])
print(L) #[1,[3,4]] print(L) #[1,3,4]
print(len(l)) #2 Print(len(L)) #3
insert()
The append and extend method inserts at the end of the list
The insert() inserts the element at the specified index in a list
The element can be added anywhere in between the list.
Syntax:
List.insert(<index>,<item>) # takes 2 arguments and returns no values
Num=[23,54,34,44,35,66,27,88,69,54]
Num.insert(0,5)
print(Num)

Num.insert(15,5) # when the index is beyond the last index, item in added to the end of the list
Num.insert(-1,5) # Negative index can be specified to insert.
Num.insert(-15,5) # negative index is less than the first element index then element is added at beginning
List Methods -list.insert()
Insert an item at a given position.

a.insert(len(a), x)is equivalent to a.append(x).


Example
L=[]
L.insert(0,6)
print(L)
L.insert(5,15)
Output:
print(L)
[6]
L.insert(1,[3,4]) [6, 15]
print(L) [6, [3, 4], 15]
L.insert(len(L),19) 3
print(L) [6, [3, 4],15, 19]
Practice Question
Write a program to find the sum of the elements in the list.

list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Practice Question
Write a program to input a string and convert it to a list. Print the index numbers of the vowels
present in the list.

s=input("enter a string: ")


s=s.lower()
L=list(s)
l=len(L)
for i in range(l):
if L[i]=='a'or L[i]=='e'or L[i]=='i' or L[i]=='o' or L[i]=='u':
print(L[i], "is at postion",i)
pop()
Removes the item from the list.
It returns the element and removes it.
Syntax:
List.pop<index>
Num=[23,54,34,44,35,66,27,88,69,54]
Num.pop(0) # delete the first element and return it i.e. 23 will get printed
print(Num)
Num.pop() # when no index is specified it removes the last element
print(Num)
L=[]
L.pop() # raises an exception if list is already empty
remove()
The element of the list can be removed even if we don’t know the index but the value to be
deleted is known using remove()
remove() removes the first occurrence of given item from the list.
Syntax: list.remove(<value>) # Does not return anything
Num=[23,54,34,44,35,66,27,88,69,54]
Num.remove(54) # removes the first occurance of 54
print(Num)

Num.remove(100) #if the value is not present, value error is returned


Difference between remove() and pop()
Remove(x) Pop([x])
Removes first occurrence of element x Removes element at index x
from the list

Raises ValueError incase value does Raises IndexError incase index does
not exist not exist

Argument is mandatory Argument is optional


clear()
The clear() removes all the items from the list and the list becomes empty after the function.
Syntax:
List.clear()
Num.clear() # Removes all elements of the list
print(Num) # prints empty list
del()
Removes all the elements as well as the list structure.
Syntax: del(<listname>)
Num=[23,54,34,44,35,66,27,88,69,54]
del(Num[4]) # Deletes the 4th element but does not return anything
del(Num[1:3]) # Deletes the element at index 1 and 2 i.e. values 54 and 34
del(Num) # deletes the entire list
print(Num)
Difference between del() and clear()
del(x[]) clear()
Deletes the element of specified index Removes all elements from the list and
list becomes empty

Argument is required Argument is optional

Deletes the list also Empty list is still existing


List Functions

len() Index() append() extend() insert()

pop() remove() clear() count() sort()

min() max() sum()


len()
The len() returns the length of the list. i.e. number of elements in the list
Syntax:
len(<list>)

L=[1,2,3,None]

Print(len(L)) ?
index()
This function returns the index of first matched item from the list
Syntax:
List.index(<item>)
Example:
Num=[23,54,34,44,35,66,27,88,69,54]
Num.index(54) # return 1

Num.index(10) # value error : 10 is not in list


append()
The append() method adds an item to the end of the list.
Syntax:
List.append(<item>) # it takes exactly one element and returns no value
Example:
Num=[23,54,34,44,35,66,27,88,69,54]
Num.append(55) # adds 55 to the end of the list, it modifies the existing list
print(Num)
Num.append([55,10])

Num.append(55,10)
append()
append() is equivalent to a[len(a):] = [x].
Example 1
l=[4]
l.append(5) Output:
print(l)
[4, 5]
[4, 5, [6]]
l.append([6])
[4, 5, [6], (4, 5)]
print(l)
l.append((4,5))
print(l)
extend()
The extend() method is used for adding multiple elements (given in the form of a list) to a list.
Syntax:
List.extend(<list>) # takes exactly one element (a list type) and returns no value
Example:
L1=[1,2,3]
L2=[4,5]
L1.extend(L2)
print(L1)
print(L2)
L3=L1.extend(L2) # L3 will return None as extend() does not return anything
print(L3)
List Methods
(extend)
list.extend(iterable) -Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] =iterable.
Example 1:
L=[1,2]
L.extend([3,4])
print(L)
L.extend(‘bye’) Output:
print(L) [1, 2, 3, 4]
L.extend((9,10)) [1, 2, 3, 4, 'b', 'y', 'e']
print(L) [1, 2, 3, 4, 'b', 'y', 'e', 9, 10]
L.extend(4) Error
print(L)
Append() Extend()
Append adds one element Extend adds a sequence to
to the list the list
Difference Element can be simple or Element has to be
between sequential data type sequence only
extend and Element will be added as a Element will be split into
single element each individual item
append
Eg Eg
L=[1] L=[1]
L.append([3,4]) L.extend([3,4])
print(L) #[1,[3,4]] print(L) #[1,3,4]
print(len(l)) #2 Print(len(L)) #3
insert()
The append and extend method inserts at the end of the list
The insert() inserts the element at the specified index in a list
The element can be added anywhere in between the list.
Syntax:
List.insert(<index>,<item>) # takes 2 arguments and returns no values
Num=[23,54,34,44,35,66,27,88,69,54]
Num.insert(0,5)
print(Num)

Num.insert(15,5) # when the index is beyond the last index, item in added to the end of the list
Num.insert(-1,5) # Negative index can be specified to insert.
Num.insert(-15,5) # negative index is less than the first element index then element is added at beginning
List Methods -list.insert()
Insert an item at a given position.

a.insert(len(a), x)is equivalent to a.append(x).


Example
L=[]
L.insert(0,6)
print(L)
L.insert(5,15)
Output:
print(L)
[6]
L.insert(1,[3,4]) [6, 15]
print(L) [6, [3, 4], 15]
L.insert(len(L),19) 3
print(L) [6, [3, 4],15, 19]
Practice Question
Write a program to find the sum of the elements in the list.

list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Practice Question
Write a program to input a string and convert it to a list. Print the index numbers of the vowels
present in the list.

s=input("enter a string: ")


s=s.lower()
L=list(s)
l=len(L)
for i in range(l):
if L[i]=='a'or L[i]=='e'or L[i]=='i' or L[i]=='o' or L[i]=='u':
print(L[i], "is at postion",i)
pop()
Removes the item from the list.
It returns the element and removes it.
Syntax:
List.pop<index>
Num=[23,54,34,44,35,66,27,88,69,54]
Num.pop(0) # delete the first element and return it i.e. 23 will get printed
print(Num)
Num.pop() # when no index is specified it removes the last element
print(Num)
L=[]
L.pop() # raises an exception if list is already empty
remove()
The element of the list can be removed even if we don’t know the index but the value to be
deleted is known using remove()
remove() removes the first occurrence of given item from the list.
Syntax: list.remove(<value>) # Does not return anything
Num=[23,54,34,44,35,66,27,88,69,54]
Num.remove(54) # removes the first occurance of 54
print(Num)

Num.remove(100) #if the value is not present, value error is returned


Difference between remove() and pop()
Remove(x) Pop([x])
Removes first occurrence of element x Removes element at index x
from the list

Raises ValueError incase value does Raises IndexError incase index does
not exist not exist

Argument is mandatory Argument is optional


clear()
The clear() removes all the items from the list and the list becomes empty after the function.
Syntax:
List.clear()
Num.clear() # Removes all elements of the list
print(Num) # prints empty list
del()
Removes all the elements as well as the list structure.
Syntax: del(<listname>)
Num=[23,54,34,44,35,66,27,88,69,54]
del(Num[4]) # Deletes the 4th element but does not return anything
del(Num[1:3]) # Deletes the element at index 1 and 2 i.e. values 54 and 34
del(Num) # deletes the entire list
print(Num)
Difference between del() and clear()
del(x[]) clear()
Deletes the element of specified index Removes all elements from the list and
list becomes empty

Argument is required Argument is optional

Deletes the list also Empty list is still existing


Q1. Which of the following is a standard Python library
function and not an exclusively list function?
A)append()
RECAP B) remove()
C)pop()
D)len()

Answer: len()
Q2. Which of the following can add only one value to a list?
A)append()
RECAP B) extend()
C)add()
D)none of these

Answer: append()
Q3. Which of the following can delete an element from a list
if the value is given?
A) del()
RECAP B) remove()
C)pop()
D)all of these

Answer: remove()
Q4. Which of the following searches for an element in a list
and returns its index?
A) search()
RECAP B) find()
C)index()
D)lsearch()

Answer: index()
Recap
Predict the output of the code given below:
L=['p','w','r','d','a']
L.remove('r’) # no output
print(L)
print(L.pop())
del L[1] No output

print(L)
Recap
Predict the output of the code given below:

L1=[10,20,30,40]
L1.clear()
print(L1)
Empty List is printed

L1=[10,20,30,40]
del(L1)
print(L1)
min()
Returns minimum or smallest element of the list
Syntax:
min(<listname>)
List1=[14,23,45,65,34,12,25,67] Return : 12

min(List1)

L=["12",'Arjun',"_@_","jiya","94"] Return : ‘12’


Since the ASCII value of 1 is least (49) out of all the other
min(L) characters
max()
Returns maximum or largest element of the list
Syntax:
max(<listname>)
List1=[14,23,45,65,34,12,25,67] Return : 67

max(List1)

L=["12",'Arjun',"_@_","jiya","94"] Return : ‘jiya’


Since the ASCII value of ‘j’ is largest (106) out of all the
max(L) other characters
sum()
Returns the sum of elements of the list

List1=[14,23,45,65,34,12,25,67]

sum(List1)
Return : 285
L=["12",'Arjun',"_@_","jiya","94"]

sum(L)
The str class contains the split method, which is useful for
splitting items in a string into a list. For example, the
following statement:

items = "Jane John Peter Susan".split()


splits the string ‘items’ into the list
Splitting a String ['Jane', 'John', 'Peter‘,'Susan’]
into a List
In this case the items are delimited by spaces in the string.
You can use a nonspace delimiter. For example, the
following statement:
items = "09/20/2012".split("/")
splits the string into the list
['09', '20', '2012']
Taking input of list elements from user
To take input of list elements from the user there are 3 ways:
1. list(input())
2. eval(input())
3. Declare an empty list and keep appending the values in a list
Taking input as a list (list())
L=list(input("enter list values:="))
print(L)

Note: Every character input is converted to an element of the list


Limitation: If we need to enter more than one digit number or create a list of strings then this
method cannot be used.
Taking input as a list (eval())
L=eval(input("enter list values:="))
print(L)

Note: The input needs to be given as list i.e. in square brackets [ ]


Appending elements to a list (append())
L=[]
n=int(input("enter number of elements"))
for i in range(n):
x=int(input("enter list element"))
L.append(x)
print(L)
Practice Question
Write a program to input a list of numbers and print all numbers divisible by 5.

L=[]
n=int(input("enter number of elements"))
for i in range(n):
x=int(input("enter list element"))
L.append(x)
for j in L:
if j%5==0:
print(j)
Practice Question
WAP to count the frequency of a given element in a list of numbers.

Sample output
L=eval(input("Enter List elements"))
print("original list: ", L)
x=int(input("enter item to search:"))
count=0
for i in L:
if i==x:
count+=1
print("The element ",x, "occurs ",count, " times")
Practice Question
WAP to find the minimum element from a list of element along with its index in the list

L=eval(input("enter list values:="))


print(L) Sample output
length=len(L)
min_ele=L[0]
min_index=0
for i in range(1,length):
if L[i]<min_ele:
min_ele=L[i]
min_index=i

print("The min element is: ",min_ele, "at index: ",min_index)


Practice Question
WAP to search for an element in the list.
L=eval(input("enter list values:="))
print(L)
x=int(input("enter element to be searched"))
for i in L:
if i==x:
print("element found")
break
else:
print("element not found")

You might also like