CBSE Class 11: Python List 5

Python List Methods

Methods that are available with list object in Python programming are given below.

They are accessed as list.method().

Python List Methods

append() – Add an element to the end of the list

extend() – Add all elements of a list to the another list

insert() – Insert an item at the defined index

 

append()

Helps us to add an element to the end of the list

#append method

n=[1,2,3,4,5]

print(n)

#[1, 2, 3, 4, 5]

n.append(6)

print(n)

#[1, 2, 3, 4, 5, 6]

n=[1,2,3,4,5]
print(n)
n.append(10)
n.append(20)
n.append(30)
print(n)

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 10, 20, 30]

extend() :

Add all elements of a list to the another list

#extend() method

n=[1,2,3,4,5]
print(n)

Output:
[1, 2, 3, 4, 5]

n.extend([6,7,8])
print(n)

Output:
[1, 2, 3, 4, 5, 6, 7, 8]

 

n=[1,2,3,4,5]
print(n)
n.extend([10,20,30])
print(n)

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 10, 20, 30]

insert() :

Insert an item at the defined index

 

0

1

2

3

4

1

2

3

4

5

#insert method

Example:

n=[1,2,3,4,5]

print(n)

#Output: [1, 2, 3, 4, 5]

n.insert(1,10)

print(n)

#Output: [1, 10, 2, 3, 4, 5]

n.insert(4,40)

print(n)

#Output: [1, 10, 2, 3, 40, 4, 5]

Example:

#insert method

n=[1,2,3,4,5]

print(n)

#Output:  [1, 2, 3, 4, 5]

n.insert(1,10)

print(n)

#Output:[1, 10, 2, 3, 4, 5]

Example:

n=[1,2,3,4,5]

print(n)

n.insert(2,20)

print(n)

#Output : [1, 2, 20, 3, 4, 5]

Example:

n=[1,2,3,4,5]

print(n)

#Output:  [1, 2, 3, 4, 5]

n.insert(3,30)

print(n)

#Output : [1, 2, 3, 30, 4, 5]

#1
n=[1,2,3,4,5]
print(n)
n.insert(2,200)
print(n)

#2
n=[1,2,3,4,5]
print(n)
n.insert(4,600)
print(n)

Output:

[1, 2, 3, 4, 5]
[1, 2, 200, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 600, 5]