Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

How to Remove Element From the List in Python

There are some methods to remove elements from the Python list. But del statement is an easy way to remove any element from the list by using an index of the list. Let’s understand it with del statement example in Python.
 

Delete item from list using del statement in Python.


output:
['a', 'b', 'd', 'e']

In the above example, ‘c’ which is at index 2 is removed by using del statement.
Delete range of items in a list by using del statement in Python

Look at the following example

output
['a', 'd', 'e']

In the above example, we remove a slice of items from the list. This is the unique capability of del statement which cannot be achieved by using pop() method.

 

Remove all items of list by using del statement

We can use del statement to remove all the items or elements from a list.

Output:
[]

 

Python pop() method to remove the item from the list

pop() method removes the item in the given positon and return it.

Output:
['a', 'b', 'd', 'e']

If no index is specified in the argument of pop() method. The pop() method returns last item of the list and return it.

output:
['a', 'b', 'c', 'd']
The last item of above list is ‘e’ which is removed by pop() method if parameter left empty.

Loading...
LearnAndLearn.com © 2018 - All rights reserved