In this notebook, I will go over different ways of removing items from Python list.
Let us create a list of numbers.
list_of_numbers = [i for i in range(20)]
list_of_numbers
Python list.clear() will remove all the elements from a list.
list_of_numbers.clear()
list_of_numbers
list_of_numbers = [i for i in range(20)]
Python list.pop() method removes the element using index. If there is no index specified, it removes the last element from the list.
list_of_numbers.pop()
Above command returns the index of the element which is removed from the list. Above command will remove the 20th element from the list.
list_of_numbers
Let us remove the element from the list by index.
list_of_numbers.pop(7)
If we provide an index which is not in the list, Python list will throw an error.
list_of_numbers.pop(20)
list_of_numbers
We can also remove an element from list by value.
For example let us remove the element 16 from the list.
list_of_numbers.remove(16)
list_of_numbers
Using del, we can remove the element by index as we can do using pop().
del list_of_numbers[0]
list_of_numbers
To remove the last element from the list, specify -1 as index.
del list_of_numbers[-1]
list_of_numbers
Using del, we can also delete a range of numbers. In the example below, we have specified the range as 0:1, which means starting from zeroth index delete everything until index 1 (not including value at index 1).
del list_of_numbers[0:1]
list_of_numbers
In below example, values at index 0 and 1 will be deleted.
del list_of_numbers[0:2]
list_of_numbers
We can also use del to remove items at fixed number of intervals.
In below example, we are deleting every 2nd number from index 2 to 8.
del list_of_numbers[2:8:2]
list_of_numbers
Another example: We are deleting every 3rd number starting from index 0 to 8.
del list_of_numbers[0:8:3]
list_of_numbers
If we want to remove elements using a condition, Python list comprehensions are very useful.
Let us remove all the elements which are multiple of 2.
print([i for i in list_of_numbers if i % 2 != 0])
All the above list removal methods also work even if list contains a data type which is not numbers.
list_of_strings = ['John', 'Stacy', 'Renee', 'Jeff']
list_of_strings.pop()
list_of_strings.remove('Stacy')
list_of_strings
Related Notebooks
- Five Ways To Remove Characters From A String In Python
- Return Multiple Values From a Function in Python
- How to Generate Embeddings from a Server and Index Them Using FAISS with API
- How to Convert Python Pandas DataFrame into a List
- R List Tutorial
- How to Plot a Histogram in Python
- Time Series Analysis Using ARIMA From StatsModels
- An Anatomy of Key Tricks in word2vec project with examples
- Python IndexError List Index Out of Range