How to iterate over a generator?

Suppose I have a large list and I want to iterate over it.

>>> x=[]
>>> for i in x:
print(x)

      

but since the list is too long, using a generator is the best way:

>>> g=(i for i in range(10))
>>> g.__next__()
0

      

But there is a problem with the number of times to iterate. Since I don't know how many times I should use g.__next__()

, I need something more dynamic.

For example:

for i in x:

      

It doesn't matter how long x is, like a loop iterating to the end.

How can I iterate with generators?

+3


source to share


2 answers


The syntax for

can be used with generators:



>>> g=(i for i in range(10))
>>> g
<generator object <genexpr> at 0x7fd70d42b0f0>
>>> for i in g:
...     print i
... 
0
1
2
3
4
5
6
7
8
9

      

+3


source


Use for a loop as with a list, Example -



for i in g:
    print(i)

      

+2


source







All Articles