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