Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: building new list from existing by dropping every n-th element

Tags:

python

list

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?

like image 820
solarisman Avatar asked Dec 02 '22 19:12

solarisman


1 Answers

>>> [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.

like image 145
Muhammad Alkarouri Avatar answered Dec 10 '22 12:12

Muhammad Alkarouri