Reputation: 859
Assume a big list and I want to iterate over it.
>>> x=[]
>>> for i in x:
print(x)
but because the list is too big, using the generator is the best way:
>>> g=(i for i in range(10))
>>> g.__next__()
0
But there is a problem with number of times to iterate.
Because I don't know how many times I should use g.__next__()
, I need something more dynamic.
For example:
for i in x:
It is not important how long is x as the loop with iterate to the end.
How can I similarly iterate using generators?
Upvotes: 3
Views: 3207
Reputation: 312259
You can use the for
syntax 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
Upvotes: 3
Reputation: 91009
Use for loop , just as you used in case of list , Example -
for i in g:
print(i)
Upvotes: 2