How to Remove Elements from Lists in Python: First, Last, and Every Nth
This guide explains how to remove elements from Python lists, focusing on three common scenarios: removing the first N elements, removing the last N elements, and removing every Nth element. We'll primarily use list slicing, the most efficient and Pythonic approach, and briefly discuss alternatives.
Removing the First N Elements
Using Slicing (Recommended)
Slicing is the most concise and efficient way to create a new list without the first N elements:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
n = 2
new_list = my_list[n:] # Slice from index n to the end
print(new_list) # Output: ['c', 'd', 'e', 'f']
print(my_list) # Output: ['a', 'b', 'c', 'd', 'e', 'f'] # Original list unchanged
- The slice
my_list[n:]
creates a new list from indexn
up to the end of the list.
Using del
(In-Place Modification)
If you want to modify the original list in-place, use del
with slicing:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
n = 2
del my_list[:n] # Delete the first n elements
print(my_list) # Output: ['c', 'd', 'e', 'f']
del my_list[:n]
: Deletes the slice from the beginning of the list up to (but not including) indexn
. This modifiesmy_list
directly.
Removing the Last N Elements
Using Negative Slicing (Recommended)
Use negative slicing to create a new list without the last N elements:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
n = 2
new_list = my_list[:-n] # Slice from beginning up to (but not including) -n
print(new_list) # Output: ['a', 'b', 'c', 'd']
my_list[:-n]
: Creates a new list containing all elements from the beginning up to (but not including) the lastn
elements.
Using del
and Slicing (In-Place Modification)
To modify the original list in-place, use del
with a negative slice:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
n = 2
del my_list[-n:] # Delete the last n elements
print(my_list) # Output: ['a', 'b', 'c', 'd']
del my_list[-n:]
: Deletes the slice from the nth-to-last element to the end of the list, modifyingmy_list
directly.
Handling Empty Lists
If n
is 0, using negative slicing with del
might seem like it would do nothing, but it will delete the entire list. Always check if n
is greater than 0 before using negative slicing with del
:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']
n = 0
if n > 0: # Only delete if n is positive
del my_list[-n:]
print(my_list) # Output: ['a', 'b', 'c', 'd', 'e', 'f']
Removing Every Nth Element
To remove every Nth element, use slicing with a step:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 3
del my_list[n-1::n] # Start at index n-1 and remove every nth
print(my_list) # Output: [1, 2, 4, 5, 7, 8]
- The third parameter to slicing is the step. In this case the step is
n
. del my_list[n-1::n]
:n-1
: The starting index. It isn-1
because the list is zero-indexed.::n
: This slice uses a step ofn
. It starts at indexn-1
and then selects everyn
th element from there to the end.del
then removes those elements.