Thanks for helping me! My question been answered in the comments, by @juanpa.arrivillaga . Key point of my question is about how python know "I am trying to assign the first element to i and the second element to string".
I am learning python, but how does [string for i, string in enumerate(a)] work really troubles me.
Here are 2 example code I write while learning python
a = ['a','b','c', 'd']
d = [string for string in enumerate(a)]
print (d)
it would return '[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]'. However, if I write the following code
a = ['a','b','c', 'd']
c = [string for i, string in enumerate(a)]
print(c)
it would return ['a', 'b', 'c', 'd']
In my understanding, string in enumerate(a) would translated to the "enumerated object" like position inside RAM. and I do not tell python what the i is (I did not tell python i is the index or string is the element). So, the code would be explained as "list["enumerated object" iterate inside "i"]", but since I did not tell python what i is, it will run into error. However, it returned a list of elements from enumerate.
Where do python learned from my code the string means element inside enumerate, and i means the index?
So, two things you need to understand. First, what is
enumerateand second, how iterable unpacking works.enumeratetakes an iterable as it's first argument and astartkeyword argument (that defaults to0if not passed explicitly). It returns an iterator of pairs, i.e. of tuples of length 2, where the first element areints starting atstartand increasing by one, and the second element comes from the original iterable you passed toenumerate.Now, you need to understand iterable unpacking in assignment targets. Note, in the
forclause of a for-loop or list comprehension (or dict/set comprehensions or generator expressions), you are assigning to a target. So:Because, at the beginning of each iteration, you get the next value from the iterator created by the iterable in the
inclause. Anything that goes in:Can also go:
But assignment targets can be more than a simple, single variable. The simplest extension, unpack into exactly two variables:
It can get more elaborate than that but I think you already understand that.
So
for i, string in whateveris you telling Python:I expect every element in
whatever(itself an iterable) to be some iterable with exactly two elements. On each iteration, assign the first item toiand the second tostring. This is simply based on position, the names don't matter. They could befor banana, apple in whateverand it works the exact same way.