Search code examples
pythonvariablesdeclare

python some case of declaring muti-variable confused me


Here's the code1:

x = [0, 1]
i = 0
j=0
i,x[i]=1,2
#print i,x
#1,[0,2]

Here's the code2:

x=0
y=1
x,y=3,x
#print x,y
#3,0

i know that python is assign variables at the same time when there are mutiple variables need to assignment.

but why the result of code1 is 1,[0,2]?shouldn't it be 1,[2,1]-- not the same time ?

I mean assign x[i],variable "i" should be 0,cuz "that time" variable "i" is 0,so it should be i,x[0]=1,2. But it is not. :(


Solution

  • You understanding is a bit wrong , Python does not assign the variables at the same time , it's just that the right hand side is first evaluated completely before assignment starts, and only after that assignment to left hand side starts , the assignment to left hand side is still sequential internally , so in first case i's value is changed before it is used again in 'x[i]' .

    The difference in the first place comes because you are changing and using value of 'I' in the left hand side .