How about adding slice notation to iterators/generators?

Eloff dan.eloff at
Fri Oct 16 03:29:51 CEST 2009

I was just working with a generator for a tree that I wanted to skip
the first result (root node.)

And it occurs to me, why do we need to do:

import sys
from itertools import islice

my_iter = islice(my_iter, 1, sys.maxint)

When we could simply add slice operations to generators?

for x in my_iter[1:]:

The way I figure it, only if there is no __getitem__ defined, and the
object has an __iter__ (i.e. not a list, but a iter(list) would be
ok), then there should be a default __getitem__ that is really just
islice, with similar limitations (no negative indices.)

The idea might need a bit of polish, but fundamentally it seems like
it could make it easier to deal with slicing generators?

At the least, stop=sys.maxint, step=1, and islice needs to accept
kwargs. So you could do islice(my_iter, start=1), that's an oversight

More information about the Python-list mailing list