+ 5
Can you please explain the output of this code?
a = enumerate(range(10)) b = enumerate(range(1,10)) c = list(zip(a,b)) print(c[-1]) Answer is ((8,8),(8,9))
2 Réponses
+ 4
Enumerate takes an iterable and gives an index to each item.
That makes looping easier in some situations, because you can access the item *and* index it in the list or whatever.
enumerate('abc')
... becomes...
(0, 'a'), (1, 'b'), (2, 'c').
The last element of a is (9, 9), the last element of b (8, 9).
Zip combines two iterables to tuples, but only reads until one of them ends.
So since a is one longer, the last item in the zip situation is (8, 8).
So the last tuple from the zip would consist of (8, 8) from a and (8, 9) from b.
+ 4
Great explanation from Honfu! I just add some information about the generators that are used here.
a = enumerate(range(10)) makes a generator of type 'enumerate object'. Also b and c are objects from the same type as a.
The special thing about these generator objects is that they can only be used once. So if a is printed with print(list(a)), a is empty after this action and looks like []. The same happend when c is created with: c = list(zip(a,b)).
After this action, a and b are empty generators, c can still be printed. But after that it is laso empty.
This behavior is the same for all generators.