Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the nth item of a generator in Python

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.

like image 797
Oliver Zheng Avatar asked Feb 20 '10 02:02

Oliver Zheng


2 Answers

one method would be to use itertools.islice

>>> gen = (x for x in range(10)) >>> index = 5 >>> next(itertools.islice(gen, index, None)) 5 
like image 121
cobbal Avatar answered Sep 19 '22 08:09

cobbal


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

from itertools import islice, count next(islice(count(), n, n+1)) 
like image 41
Mark Byers Avatar answered Sep 21 '22 08:09

Mark Byers