How to Clear a Python List

To clear a whole list in Python, use the clear() method.

For example:

numbers = [1, 2, 3, 4, 5]
numbers.clear()

print(numbers)

Output:

[]

If you want to remove an item at a specific index, use the pop() method.

For example, let’s remove the second element of a list:

nums = [1,2,3]
nums.pop(1)

print(nums)

Output:

[1, 3]

All in all, there are four ways to remove elements from a list in Python:

  1. The clear() method.
  2. The pop() method.
  3. The remove() method.
  4. The del statement.

Let’s go through each of these.

1. Clear() in Python

To completely clear a list in Python, use the built-in clear() method.

For example:

numbers = [1, 2, 3, 4, 5]
numbers.clear()

2. Pop() Method in Python

You can remove an element with a specific index with pop() method.

To do this, pass it the index of the item you want to remove. (And remember that Python indexing begins from 0):

For example, let’s remove the second number of a list of numbers:

nums = [1,2,3]
nums.pop(1)

Notice the pop() method also returns the removed value. If you need to store it somewhere, you don’t need to do it separately.

3. Remove() Method in Python

To remove a first element that matches with a criterion, use the remove() method. To do this, pass the element you want to remove into the method.

For instance, let’s remove the first occurrence of a number 2 in the list of numbers:

nums = [1,1,2,2,3,3]
nums.remove(2)

print(nums)

Output:

[1,1,2,3,3]

4. The del Statement in Python

You can also remove elements from a list using the del statement.

To do this specify the index of the element you wish to remove:

nums = [1,2,3]
del nums[0]

print(nums)

Output:

[2, 3]

In contrast to the pop() method, the del statement only deletes the element and does not return it.

Conclusion

  • To clear a whole Python list, use the clear() method of a list.
  • To remove an element at a specific index, use the pop() method or the del statement.
  • To remove the first occurrence of an element in a list, use the remove() method.

Thanks for reading.

Happy coding!

Further Reading

How to Add to a List in Python

50 Python Interview Questions

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *