How to remove an element from a list in Python?

PythonServer Side ProgrammingProgramming

A list in Python is a linear data structure where elements are stored in contiguous memory locations and elements are accessed by their indexes.

We may sometimes need to remove an element from a list in Python. There are various inbuilt functions to achieve this.

pop()

This deletes or removes the element at the index passed as an argument in pop().

Example

 Live Demo

lst=[1,2,3,4,5]
lst.pop(2)
print(lst)

Output

[1, 2, 4, 5]

The above code snippet shows that the pop(2) removes the element at index 2.

remove()

This function removes the first occurrence of the element passed as argument in remove().

Example

 Live Demo

lst=[1,2,3,2,4,5]
lst.remove(2)
print(lst)

Output

[1, 3, 2, 4, 5]

The above code snippet shows that the remove(2) removes the first occurrence of element 2 ,i.e. at index 1.

del[a:b]

This function is used to remove elements from index a(inclusive) to index b(not inclusive) in a list.

Example

 Live Demo

lst=[0,1,2,3,4,5,6,7,8,9]
del lst[2:5]
print(lst)

Output

[0, 1, 5, 6, 7, 8, 9]

The above code removes the elements from index 2 to 5 (i.e. elements 2,3,4) from the list.

clear()

This function is used to remove all the elements from the list.

Example

 Live Demo

lst=[0,1,2,3,4,5,6,7,8,9]
lst.clear()
print(lst)

Output

[]

All the elements are removed from the list, but an empty list is left.

raja
Published on 11-Mar-2021 09:25:14
Advertisements