e Learning

How to Remove an Element from List by Index in Python

In Python, we can use the pop() function to remove an element from a list by the index.

list.pop(index)

The following code shows how it works:

countries = ['Italy', 'Brazil', 'Spain', 'Sweden']
print(countries)

countries.pop(1)

print(countries)

In the preceding example, we removed the index position 1, which corresponds to the second item (Brazil) in the list called countries.

The pop() method removes the last item in a list if you invoke pop() without an index.

If you want, you can delete an item and store it in a variable at the same time. The following code shows how it works:

countries = ['Italy', 'brazil', 'Spain', 'sweden']
print(countries)

removed = countries.pop(1)

print(countries)
print(removed)

Removing an Item from list by index Using the del Statement

The del statement also can be used to remove an item from a list by index.

The following Python code example shows how it works:

countries = ['Italy', 'brazil', 'Spain', 'sweden']
print(countries)

del countries[2]

print(countries)

In this example, the third element is removed by passing the index position (2) as an argument.