To keep every nth element in a list in Python, the easiest way is to use slicing.
lst = [1, 2, 3, 4, 5, 6, 7]
every_3rd = lst[::3]
print(every_3rd)
#Output:
[1, 4, 7]
If you want to create a function which will keep every nth element in a list, you can do the following:
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]
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 keeping every nth element in a list.
To keep every nth element of a list in Python, you can use slicing and pass n for the step size.
For example, if you have a list and you want every 2nd element, starting with the first element, you would get the slice defined by [::2] as shown below.
lst = [1, 2, 3, 4, 5, 6, 7]
every_2nd = lst[::2]
print(every_2nd)
#Output:
[1, 3, 5, 7]
If you want to create a function which will keep every nth element in a list given a list and n, you can use the following:
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]
If you want to start with a different element, then you can adjust the starting point of your slice.
Removing Every Nth Element from a List in Python
If you want to go the other way and remove every nth element from a list in your Python code, you can also use slicing.
In this case, we will need to adjust the slice we take and also utilize the Python del keyword to delete elements from the list.
Below is a function which will remove every nth element from a list given a list and n in Python.
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]
Hopefully this article has been useful for you to learn how to keep every nth element in a list in Python.