- Remove an item from a list in Python (clear, pop, remove, del)
- Remove all items: clear()
- Remove an item by index and get its value: pop()
- Remove an item by value: remove()
- Remove items by index or slice: del
- Remove items that meet the condition: List comprehensions
- Delete All Elements Of A List In Python
- Delete All Elements Of A List In Python Using The clear() Method
- Delete All Elements Of A List In Python Using The del Statement
- Delete All Elements Of A List In Python Using The * Operator
- Conclusion
- Related
- Recommended Python Training
- How to Clear a Python List [4 Ways & Examples]
- 1. Clear() in Python
- 2. Pop() Method in Python
- 3. Remove() Method in Python
- 4. The del Statement in Python
- Conclusion
Remove an item from a list in Python (clear, pop, remove, del)
In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using the del statement by specifying a position or range with an index or slice. Additionally, you can utilize list comprehensions to remove items that meet a specific condition.
To learn how to add an item to a list, see the following article:
Remove all items: clear()
You can remove all items from a list with clear() .
Remove an item by index and get its value: pop()
You can remove the item at the specified position and get its value with pop() . The index starts at 0 (zero-based indexing).
l = [0, 10, 20, 30, 40, 50] popped_item = l.pop(0) print(popped_item) # 0 print(l) # [10, 20, 30, 40, 50] popped_item = l.pop(3) print(popped_item) # 40 print(l) # [10, 20, 30, 50]
Negative values can be used to specify a position from the end of the list, with the last index being -1 .
popped_item = l.pop(-2) print(popped_item) # 30 print(l) # [10, 20, 50]
If no argument is provided, the last item in the list is removed.
popped_item = l.pop() print(popped_item) # 50 print(l) # [10, 20]
Specifying a nonexistent index will result in an error.
# popped_item = l.pop(100) # IndexError: pop index out of range
Note that using pop(0) to remove the first item is an O(n) operation and is inefficient. For the computational complexity of various operations on lists, see the official Python wiki:
To remove the first item with O(1) complexity, use the deque type provided in the standard library’s collections module. For example, when treating data as a queue (FIFO), deque is a more efficient option.
Remove an item by value: remove()
You can remove the first item in the list whose value equals the specified value with remove() .
l = ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave'] l.remove('Alice') print(l) # ['Bob', 'Charlie', 'Bob', 'Dave']
If the list contains more than one item with the specified value, only the first occurrence is deleted.
l.remove('Bob') print(l) # ['Charlie', 'Bob', 'Dave']
To remove multiple items that meet a specific condition at once, use list comprehensions as described below.
If you specify a nonexistent value, an error will be raised.
# l.remove('xxx') # ValueError: list.remove(x): x not in list
You can use the in operator to check if a list contains a specific item.
Remove items by index or slice: del
In addition to the list methods, you can remove elements from a list using the del statement.
Specify the item to be deleted by index. The first index is 0 , and the last is -1 .
l = [0, 10, 20, 30, 40, 50] del l[0] print(l) # [10, 20, 30, 40, 50] del l[3] print(l) # [10, 20, 30, 50] del l[-1] print(l) # [10, 20, 30] del l[-2] print(l) # [10, 30]
You can delete multiple items with slice notation.
l = [0, 10, 20, 30, 40, 50] del l[2:5] print(l) # [0, 10, 50] l = [0, 10, 20, 30, 40, 50] del l[:3] print(l) # [30, 40, 50] l = [0, 10, 20, 30, 40, 50] del l[-2:] print(l) # [0, 10, 20, 30]
It is also possible to delete all items by specifying the entire range.
l = [0, 10, 20, 30, 40, 50] del l[:] print(l) # []
You can specify step as [start:stop:step] .
l = [0, 10, 20, 30, 40, 50] del l[::2] print(l) # [10, 30, 50]
See the following article for details on slices.
Remove items that meet the condition: List comprehensions
Removing items that satisfy a specific condition is equivalent to extracting items that do not satisfy the condition.
To achieve this, use list comprehensions.
An example of removing odd or even items (i.e., keeping even or odd items) is as follows. % is the remainder operator, and i % 2 calculates the remainder when dividing i by 2 .
When using list comprehensions, a new list is created, leaving the original list unchanged. This is different from using list type methods or the del statement.
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] evens = [i for i in l if i % 2 == 0] print(evens) # [0, 2, 4, 6, 8] odds = [i for i in l if i % 2 != 0] print(odds) # [1, 3, 5, 7, 9] print(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
For details on extracting elements using list comprehensions, see the following article:
Here are other examples of using list comprehensions:
l = ['Alice', 'Bob', 'Charlie', 'Bob', 'David'] print(l) # ['Alice', 'Bob', 'Charlie', 'Bob', 'David'] print([s for s in l if s != 'Bob']) # ['Alice', 'Charlie', 'David'] print([s for s in l if s.endswith('e')]) # ['Alice', 'Charlie']
For examples involving a list of strings, see the following article:
To remove duplicate elements from a list, use set() :
print(list(set(l))) # ['Alice', 'Charlie', 'David', 'Bob']
Delete All Elements Of A List In Python
In python, we use lists in almost every program. We have already discussed ways to compare two lists and to reverse a list in python. In this article, we will discuss different ways to delete all the elements of a list in python.
Delete All Elements Of A List In Python Using The clear() Method
The pop() method is used to delete the last element of a list. When invoked on a list, the pop() method returns the last element of the list and deletes it from the list. We can use the while loop and the pop() method to remove all the elements of the list.
For this, we can keep invoking the pop() method on the list inside the while loop until the list becomes empty. Once the list becomes empty, the while loop will stop its execution and we will get a list that has no elements. You can observe this in the following program.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using the pop() method while myList: myList.pop() print("List after deleting all the elements:",myList)
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []
Instead of using the pop() method several times, we can use the clear() method to delete all the elements from a list. The clear() method, when invoked on a list, deletes all the elements of the list.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using the clear() method myList.clear() print("List after deleting all the elements:",myList)
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []
Delete All Elements Of A List In Python Using The del Statement
The del statement is used to delete an object in python. We can also use the del statement to remove the elements of a list. For this, we will create a slice of the list that contains all the elements. After that, we will delete the slice. As the slice contains references to the elements in the original list, all the elements in the original list will be deleted and we will get an empty list. You can do it as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using the del method del myList[:] print("List after deleting all the elements:", myList)
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []
Delete All Elements Of A List In Python Using The * Operator
This is one of the least used ways to remove elements from a list in Python. You might be knowing that multiplying a list to any number N repeats the elements of the list N times. In the same way, when we multiply a list to 0, all the elements of the list are deleted. So, we can multiply the given list with 0 to remove all of its elements as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("The original list is:") print(myList) # deleting elements using * myList = myList * 0 print("List after deleting all the elements:", myList)
The original list is: [1, 2, 3, 4, 5, 6, 7, 8, 9] List after deleting all the elements: []
Conclusion
In this article, we have discussed four different ways to delete all the elements of a list in python. To know more about lists in python, you can read this article on list comprehension. You might also like this article on how to get the last element of a list in python.
Related
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.
How to Clear a Python List [4 Ways & Examples]
Python list is a common data type used to store multiple values for easy access. Sometimes, you may want to clear Python lists either by removing all the elements or removing elements one by one.
This is a comprehensive guide to clearing a list in Python in 4 different ways.
The short answer: To clear the whole list in Python, use the list.clear() method.
For example, let’s wipe out a list of numbers:
numbers = [1, 2, 3, 4, 5] numbers.clear() print(numbers)
To remove an item at a specific index, use the list.pop(index) method.
For example, let’s remove the second element of a list:
nums = [1,2,3] nums.pop(1) print(nums)
All in all, there are four ways to remove elements from a list in Python:
Let’s go through each of these.
1. Clear() in Python
To completely clear a list in Python, use the built-in clear() method. This removes all the elements of the original list.
numbers = [1, 2, 3, 4, 5] numbers.clear() print(numbers)
Now there are no longer values in this list.
Notice that this is not always what you want. Sometimes you only want to get rid of particular elements of the list. The rest of this guide focuses on removing particular elements rather than wiping out the entire list.
2. Pop() Method in Python
You can remove a single element with a specific index using the list’s pop() method.
To do this, pass the index of the item you want to remove as an argument. (And keep in mind that Python indexing starts at 0):
For example, let’s remove the second number from a list of numbers:
numbers = [1,2,3] numbers.pop(1) print(numbers)
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
Another way to remove elements from a list is by using the list.remove() method to remove the first occurrence of a particular element from the list. To do this, pass the element you want to remove into the method.
For instance, let’s remove the first occurrence of the number 2 in the list of numbers:
nums = [1,1,2,2,3,3] nums.remove(2) print(nums)
4. The del Statement in Python
Last but not least, 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.
For example, let’s remove the first element of a list of numbers:
nums = [1,2,3] del nums[0] print(nums)
In contrast to the pop() method you saw earlier, 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.