0
Question to iteration and next
Who can explain that code? (Code from Code challenge) Iteration and next what does it do? A = [1, 2, 3, 4, 5, 6, 7] G = iter(A) next(G) for num in G: print(num) next(G) next(G) https://code.sololearn.com/c5yc50W3f94G/?ref=app
3 ответов
+ 3
iter() makes an iterator object
next(iterator_obj) goes to the next value in the object
+ 3
iter(A) return a generator object iterating the iterable object passed as argument...
a generator is an iterable object wich could be consumed only once (remember where it has stopped iterating if so)
next(G) return the next value in an iterable: for a generator consume one iteration at a time...
for value in G loop over (consume / iterate) the whole generator (value by value)...
first next((G) consume the first item of A, so for loop start with 2nd item of A (2 is printed), then twice next(G) consume two more items of A (3, 4) then for loop consume one more item (4 is printed), then again twice more items are consumed by both next(G), then loop exit as generator is fully consumed ^^
finally code has output only 2 and 4 ;P
0
But the answers is 25.