Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignments in python [duplicate]

Tags:

python

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.

like image 376
Jeremie Avatar asked Sep 23 '18 15:09

Jeremie


People also ask

Is it possible to do multiple assignments at once in Python?

Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left.

What is the purpose of multiple assignments in Python?

Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code.

How do you declare 3 variables in Python?

Multiple AssignmentPython allows you to assign a single value to several variables simultaneously. Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively, and one string object with the value "john" is assigned to the variable c.


2 Answers

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)

Update 2: changed related question as per @blhsing comment to a more related discussion: Python Multiple Assignment Statements In One Line

like image 89
Eduard Avatar answered Oct 09 '22 13:10

Eduard


Python variables know their types based on the type of variable assigned to it. It is a dynamically typed language. In your code, the interpreter sees foo1 = foo1[0] = [0] and it finds a value at the end, which is [0]. It is a list with one element 0. Now, this gets assigned to the first element of the list foo1 through foo1[0] = [0]. But since foo1 is already declared, it creates an object which has a pointer to itself, and hence foo1 gets self-referenced infinitely, with the innermost list having 0.

The structure of the list foo1 will be the same when the code is foo1 = foo1[0].

The object foo1 has entered an infinite self-referenced loop.

like image 30
a_r Avatar answered Oct 09 '22 14:10

a_r