views:

99

answers:

3

Is there a more syntactically concise way of writing the following?

gen = (i for i in xrange(10))
index = 5
for i, v in enumerate(gen):
    if i is index:
        return v

It seems almost natural that a generator should have a gen[index] expression, that acts as a list, but is functionally identical to the above code.

A: 

Perhaps you should elaborate more on a actual use case.

>>> gen = xrange(10)
>>> ind=5 
>>> gen[ind]
5
ghostdog74
I editted `xrange(10)` to `(i for i in xrange(10))`. Turns out this syntax works for `xrange` since it's not really a generator...
MTsoul
`xrange` predates generators, and returns an xrange object, which actually implements the full sequence protocol.
Mike Graham
+3  A: 

one method would be to use itertools.islice

>>> next(itertools.islice(xrange(10), 5, 5 + 1))
5
cobbal
I totally didn't even know about the `next()` function either. Thanks!
MTsoul
+4  A: 

You could do this, using count as an example generator:

from itertools import islice, count
islice(count(), n, n+1).next()
Mark Byers
That's it! Thanks!
MTsoul