To remove every nth element from a list in Python, the easiest way is to use slicing.
def remove_every_nth(lst, n):
del lst[n-1::n]
return lst
example = [1, 2, 3, 4, 5, 6, 7]
print(remove_every_nth(example,3))
#Output:
[1, 2, 4, 5, 7]
When working with collections of data, the ability to easily keep or remove specific items from a collection can be valuable.
One such operation in Python which is common is removing every nth element in a list.
To remove every nth element of a list in Python, utilize the Python del keyword to delete elements from the list and slicing.
For your slice, you want to pass n for the slice step size.
For example, if you have a list and you to remove every 2nd element, you would delete the slice defined by [1::2] as shown below.
lst = [1, 2, 3, 4, 5, 6, 7]
del lst[1::2]
print(lst)
#Output:
[1, 3, 5, 7]
If you want to create a function which will remove every nth element from a list given a list and n, you can use the following:
def remove_every_nth(lst, n):
del lst[n-1::n]
return lst
example = [1, 2, 3, 4, 5, 6, 7]
print(remove_every_nth(example,3))
#Output:
[1, 2, 4, 5, 7]
Keeping Every Nth Element in a List in Python
If you want to go the other way and keep every nth element in a list in your Python code, you can also use slicing.
In this case, we will need to adjust the slice we take.
Below is a function which will keep every nth element from a list given a list and n in Python.
def keep_every_nth(lst, n):
return lst[::n]
example = [1, 2, 3, 4, 5, 6, 7]
print(keep_every_nth(example,3))
#Output:
[1, 4, 7]
Hopefully this article has been useful for you to learn how to remove every nth element from a list in Python.