I want to build up a new list in which every n-th element of an initial list is left out, e.g.:
from ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']
make ['second', 'third', 'fifth', 'sixth'
because n = 3
How to do that?
Is it - first of all - correct to accomplish this by building up a new list, instead of trying to delete? For the latter I tried with deque
and rotate
but that ended up in confusion.
To build up a new list I was trying something with range(1,len(list),n)
but that are the element positions to be deleted and not the ones which are to be kept for the new list.
How do I get my desired list?
>>> [s for (i,s) in enumerate(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']) if i%3]
['second', 'third', 'fifth', 'sixth']
The answer in a few steps:
The enumerate
function gives a list of tuples with the index followed by the item:
>>> list(enumerate(['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']))
[(0, 'first'), (1, 'second'), (2, 'third'), (3, 'fourth'), (4, 'fifth'), (5, 'sixth'), (6, 'seventh')]
then you check if the index does not divide by three, and if so you include the item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With