spliting a list by nth items

Raymond Hettinger vze4rx4y at verizon.net
Thu Sep 23 17:27:41 EDT 2004


[Steven Bethard]
> so I could probably do
> something along these lines (inspired by your two suggestions):
>
> non_nth_items = [item for i, item in enumerate(items) if (i - start) % n]
>
> instead of my original
>
> non_nth_items = list(items)
> del non_nth_items[start::n]
>
> The enumerate/range solution is a little more verbose, but it does only go
> through the list once.  Thanks for the good suggestions!

The enumerate solution has a lot going for it.  It is more flexible and easily
accomodates criteria other than every nth item. More importantly, it
demonstrates an important guiding principle:  multiple list deletions are a code
smell indicating that building a new list is a better approach.  On this
newsgroup, I've seen people tie themselves in knots with multiple in-place
deletions during iteration when the new list approach was clearer, more robust,
and faster.

The runtime behavior of the non_nth_items[start::n] approach is implementation
dependent.  One can easily imagine a O(n**2) process running behind the scenes.
CPython is a smarter than that, but the code for  list_ass_subscript() in
listobject.c is not a pretty sight.


Raymond Hettinger





More information about the Python-list mailing list