views:

125

answers:

1

I have a generator function and want to get the first ten items from it; my first attempt was:

my_generator()[:10]

This doesn't work because generators aren't subscriptable, as the error tells me. Right now I have worked around that with:

list(my_generator())[:10]

This works since it converts the generator to a list; however, it's inefficient and defeats the point of having a generator. Is there some built-in, Pythonic equivalent of [:10] for generators?

+16  A: 
import itertools

itertools.islice(mygenerator, 10)

itertools has a number of utilities for working with iterators. islice takes start, stop, and step arguments to slice an iterator just as you would slice a list.

Ned Batchelder
actually use: itertools.islice( mygenerator(), 10 )
Martlark
@martlark: uhm, no Ned had correct version.
SilentGhost
@SilentGhost well, when I tried it I got this error: import itertools def sumUp(): x = 20; z = 0 for y in range(x+1): z +=1 yield z for z in itertools.islice(sumUp, 5): print zTraceback (most recent call last): File "C:\Data\code\Febrl\src\z.py", line 9, in <module> for z in itertools.islice(sumUp, 5):TypeError: 'function' object is not iterablepython 2.6
Martlark
Verified that need function call () to actually make the generator. But if you do mygenerator=sumUp() before for then SilentGhost and Ned are right. sumUp is not generator, it's result is.
Tony Veijalainen