Multiple assignments in python

  • A+
Category:Languages

I need a clear explanation here. Why does the following code work ?

foo1 = foo1[0] = [0] 

Ok, I know assignments are done left to right.

How does python understand foo1 is a list?

Btw I know foo1 ends up as [[...]] its first element being itself.

 


Because

foo1 = foo1[0] = [0] 

is equivalent to

temp = [0] foo1 = temp  foo1[0] = temp  

it first evaluates expression and then assigns from left to right. Analyzing this line by line you'll get what's going on: - first a list is created in temp - then list temp is assigned to foo1 making it a list (answers your actual question) - 3rd line just makes an assignment of first element to the list itself (thus [[...]] in output)

assigns the single resulting object to each of the target lists, from left to right from here: https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

Update: also see answers to similar question here: Multiple assignment and evaluation order in Python

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: