In PHP, to do a variable assignment "in bulk" (declare it on the same line), we can do it using the list
function.
Example:
list($a, $b, $c) = array(1, 2, 3);
How to make this type of bulk assignment in Python?
In PHP, to do a variable assignment "in bulk" (declare it on the same line), we can do it using the list
function.
Example:
list($a, $b, $c) = array(1, 2, 3);
How to make this type of bulk assignment in Python?
It's very similar:
(a, b, c) = 1, 2, 3
The concept you are referring to is called unpacking .
You can use a simple
a, b, c = 1, 2, 3
Note that this concept also serves to perform the unpacking of several different sequence types, be they tuples (as implicitly is your example) or even lists. In fact, as in Python everything is an object, you can generate the list dynamically by a function:
a, b, c = range(1, 4)
Just note that the number of variants to be assigned must be equal to the number of elements in the sequence, or a%
>>> a, b, c = range(1, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
This concept is also very useful when passing arguments to functions:
>>> from __future__ import print_function
>>> print(range(3))
[0, 1, 2]
>>> print(*range(3))
0 1 2