Difference between Python__for loop and list comprehension

Not much to say, the above example

>>> L = [1,1,1]
>>> for i in range(len(L)):
    L[i] = L[i] + L[i-1]
    print(L)

#result    
[2, 1, 1]
[2, 3, 1]
[2, 3, 4]

There is no problem, the list needs to be modified once each time through the loop,

next example

>>> L = [1,1,1]
>>> L = [L[i]+L[i-1] for i in range(len(L))]
>>> L
[2, 2, 2]

.....I don't want to talk, I stepped on this pit twice = = The reason is the equal sign = The thing on the right side of this thing will be assigned (referenced) to the left side after the calculation is complete...

The first example has an assignment statement per loop:

L[i] = L[i] + L[i-1] 

And the following list comprehension needs to be completely generated before it can be assigned to the left--

what- . - ..........

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325725779&siteId=291194637