With itertools
you will obtain another generator object so in most of the cases you will need another step the take the first N elements (N
). There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator
:
Using list comprehension:
first_N_element=[generator.next() for i in range(N)]
Otherwise:
first_N_element=list(generator)[:N]
Where N
is the number of elements you want to take (e.g. N=5 for the first five elements).