Remove Elements from a List Python by Index
Introduction
In this Byte we'll be exploring how to remove an element from a list by its index. Whether you're experienced or a novice, you probably find yourself having to do this quite frequently. In the following sections, we'll be showing a couple different methods for removing an element by index.
Python Lists and Indexing
Python lists are a type of data structure that can hold an ordered collection of items, which means you can store multiple items in a single variable. These items can be of any type and you can mix types within a single list.
my_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(my_list)
['apple', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango']
In Python, indexing syntax can be used as a substitute for the list.get()
method. Python uses zero-based indexing, so the first element has an index of 0.
print(my_list[0]) # prints 'apple'
print(my_list[2]) # prints 'cherry'
apple
cherry
How to Remove an Element by Index
There are several ways to remove an element from a list by its index in Python. The two most common methods are using the pop()
method and the del
statement. Let's go through each of them.
Using pop() Method
The pop()
method removes the element at the specified position. The method also returns the value of the removed element. This can be useful if you need to use the value after removing it from the list.
my_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
removed_element = my_list.pop(1)
print(removed_element) # prints 'banana'
print(my_list) # prints ['apple', 'cherry', 'orange', 'kiwi', 'melon', 'mango']
Output:
banana
['apple', 'cherry', 'orange', 'kiwi', 'melon', 'mango']
Note: If you use the pop()
method without an index, it removes and returns the last item in the list.
In my experience, I tend to like the pop()
method since it's both simple to use and it returns to you the value that was removed.
Using del Statement
Python's del
statement is a powerful tool that allows you to remove an element from a list by its index. This is a straightforward and efficient way to deal with unwanted elements. Let's see it in action:
fruits = ['apple', 'banana', 'cherry', 'date']
del fruits[1]
print(fruits)
Output:
['apple', 'cherry', 'date']
In this example, we're deleting the second element ('banana') from our list of fruits by referencing its index (1). Remember, Python list indexing starts at 0!
Note: Be careful when using the del
statement. If you try to delete an element at an index that doesn't exist, Python will throw an IndexError
.
Removing Multiple Elements by Index
What if you need to remove multiple elements from a list? You could use the del
statement in a loop, but there's a more efficient way. Let's create a function that accepts a list and a set of indices to be removed:
def remove_indices(input_list, indices):
indices = set(indices) # remove duplicates
input_list = [v for i, v in enumerate(input_list) if i not in indices]
return input_list
fruits = ['apple', 'banana', 'cherry', 'date']
print(remove_indices(fruits, [0, 2]))
Output:
['banana', 'date']
In this example, we're removing the first and third elements from our list by passing their indices (0 and 2) to our remove_indices
function.
Removing Elements in a Range
In other scenarios, we may need to remove a range of elements from a list. Python's slice assignment can be used to achieve this. Let's try removing elements from index 1 to 3:
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
fruits[1:3] = []
print(fruits)
Output:
['apple', 'date', 'elderberry']
Here, 'banana' and 'cherry' have been removed from the list. The slice 1:3
includes indices 1 and 2, but not 3, as Python slice ranges are up to, but not including, the end index.
Conclusion
Manipulating lists is a fundamental part of programming in Python. Whether you're removing a single element, multiple elements, or a range of elements, Python provides several ways to achieve this.