spliting a list by nth items

Michael Hoffman m.h.3.9.1.without.dots.at.cam.ac.uk at example.com
Thu Sep 23 17:15:44 EDT 2004


Ed Leafe wrote:

> nth_items = items[::n]
> non_nth_items = [item for item in items if not in nth_items]

Unfortunately, that only works if each item in items is unique. It's 
also somewhat inefficient since you traverse nth_items for each item in 
items.

 >>> n = 2
 >>> items = [5] * 5
 >>> nth_items = items[::n]
 >>> non_nth_items = [item for item in items if not in nth_items]
   File "<stdin>", line 1
     non_nth_items = [item for item in items if not in nth_items]
                                                     ^
SyntaxError: invalid syntax
 >>> # I think you meant:
 >>> non_nth_items = [item for item in items if item not in nth_items]
 >>> nth_items
[5, 5, 5]
 >>> non_nth_items
[]
--
Michael Hoffman



More information about the Python-list mailing list