Hello I’ve found an intersting snippet:
seq = ["one", "two", "three"] #edited
for i, element in enumerate(seq):
seq[i] = '%d: %s' % (i, seq[i])
>>> seq
['0: one', '1: two', '2: three']
I wonder how python is doing that…. for me element should be undefined…but obviously it isn’t..what does python do here?
Thanks a lot!
enumerateessentially turns each element of the input list into a list of tuples with the first element as the index and the element as the second.enumerate(['one', 'two', 'three'])therefore turns into[(0, 'one'), (1, 'two'), (2, 'three')]The bit just after the
forpretty much assignsito the first element andelementto the second for each tuple in the enumeration. So for example in the first iteration,i == 0andelement == 'one', and you just go through the other tuples to get the values for the other iterations.