How to remove an object from a list in Python?

PythonServer Side ProgrammingProgramming

You can use 3 different methods to remove an object from a list in Python. They are remove, del and pop. You can use them as follows −

The remove method removes the first value matching the argument to remove from the list, not a specific index. 

example

a = [3, 2, 3, 2]
a.remove(3)
print(a)

Output

This will give the output −

[2, 3, 2]

The del method removes a specific index from the list. 

example

a = [3, "Hello", 2, 1]
del a[1]
print(a)

Output

This will give the output −

[3, 2, 1]

The pop method returns the removed element. The argument to pop is the index you want to remove.

Example

a = [3, "Hello", 2, 1]
print(a.pop(1))
print(a)

Output

This will give the output −

"Hello"
[3, 2, 1]
raja
Published on 05-Jan-2018 10:26:10
Advertisements