Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignment semantics

In Python one can do:

a, b   = 1, 2 (a, b) = 1, 2 [a, b] = 1, 2 

I checked the generated bytecode using dis and they are identical.
So why allow this at all? Would I ever need one of these instead of the others?

like image 678
Aillyn Avatar asked Mar 03 '11 15:03

Aillyn


People also ask

What is multiple assignment?

multiple assignment A form of assignment statement in which the same value is given to two or more variables. For example, in Algol, a := b := c := 0. sets a, b, c to zero. A Dictionary of Computing. "multiple assignment ."

What is the syntax of multiple assignments in c?

MultipleAssignment is a language property of being able to assign one value to more than one variables. It usually looks like the following: a = b = c = d = 0 // assigns all variables to 0.

How do you declare multiple assignments in one?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

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.


1 Answers

One case when you need to include more structure on the left hand side of the assignment is when you're asking Python unpack a slightly more complicated sequence. E.g.:

# Works >>> a, (b, c) = [1, [2, 3]]  # Does not work >>> a, b, c = [1, [2, 3]] Traceback (most recent call last):   File "<stdin>", line 1, in <module> ValueError: need more than 2 values to unpack 

This has proved useful for me in the past, for example, when using enumerate to iterate over a sequence of 2-tuples. Something like:

>>> d = { 'a': 'x', 'b': 'y', 'c': 'z' } >>> for i, (key, value) in enumerate(d.iteritems()): ...     print (i, key, value) (0, 'a', 'x') (1, 'c', 'z') (2, 'b', 'y') 
like image 107
Will McCutchen Avatar answered Oct 01 '22 18:10

Will McCutchen