Get a subset of a generator

Viewed 4672

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?

2 Answers
Related