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?
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 ."
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With