How to bulk assign variables in Python?

Asked

Viewed 141 times

4

In PHP, to make a variable assignment "bulk" (declare it on the same line), we can do using the function list.

Example:

list($a, $b, $c) = array(1, 2, 3);

How to do this kind of bulk assignment in Python?

2 answers

6

The concept you refer to is called unpacking.

You can use a simple

a, b, c = 1, 2, 3

Note that such a concept also serves to perform the unpacking of several different sequence types, be it 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 variables to be assigned must be equal to the number of items in the sequence, or a ValueError:

>>> 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

6


Is very similar:

(a, b, c) = 1, 2, 3
  • 3

    does not need the parentheses on the left side. (By other, depending on the expression, it may be a good to have parentheses on the right side)

  • Shorthand...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.