Exclude every nth element from list?

Vincent Vande Vyvre vincent.vande.vyvre at telenet.be
Sat Mar 26 13:12:35 EDT 2016


Le 26/03/2016 18:06, Vincent Vande Vyvre a écrit :
> Le 26/03/2016 17:49, beliavsky--- via Python-list a écrit :
>> I can use x[::n] to select every nth element of a list. Is there a 
>> one-liner to get a list that excludes every nth element?
> Something like that:
>
> >>> l = list("lkodjuyhrtgfedcvfg")
> >>> l
> ['l', 'k', 'o', 'd', 'j', 'u', 'y', 'h', 'r', 't', 'g', 'f', 'e', 'd', 
> 'c', 'v', 'f', 'g']
> >>> ll = [c for i, c in enumerate(l) if i % 3]
> >>> ll.insert(0, l[0])
> >>> ll
> ['l', 'k', 'o', 'j', 'u', 'h', 'r', 'g', 'f', 'd', 'c', 'f', 'g']
>
>
>
> Vincent
Correction, it's more correct with the insert before the list comprehension

 >>> l.insert(0, "_")
 >>> ll = [c for i, c in enumerate(l) if i % 3]
 >>> ll
['l', 'k', 'd', 'j', 'y', 'h', 't', 'g', 'e', 'd', 'v', 'f']



More information about the Python-list mailing list