Get the nth item of a generator in Python

Solution 1:

one method would be to use itertools.islice

>>> gen = (x for x in range(10))
>>> index = 5
>>> next(itertools.islice(gen, index, None))
5

Solution 2:

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

from itertools import islice, count
next(islice(count(), n, n+1))

Solution 3:

I think the best way is :

next(x for i,x in enumerate(it) if i==n)

(where it is your iterator and n is the index)

It doesn't require you to add an import (like the solutions using itertools) nor to load all the elements of the iterator in memory at once (like the solutions using list).

Note 1: this version throws a StopIteration error if your iterator has less than n items. If you want to get None instead, you can use :

next((x for i,x in enumerate(it) if i==n), None)

Note 2: There are no brackets inside the call to next. This is not a list comprehension, but a generator comprehension, that does not consume the original iterator further than its nth element.