Use parentheses or not for multiple variable assignment in Python?

I came across these options while considering several variables:

x,y,z = 1,2,3
(x,y,z) = 1,2,3
x,y,z = (1,2,3)
(x,y,z) = (1,2,3)

I tested them, and they all seemed to assign the same values, and I checked the types of the variables, and they seem to be all int types.

So, are they all really equivalent or is there something subtle that I'm missing? If they are equivalent, what is considered correct in Python?

+4
source share
1 answer

As you already noted, they are all functionally equivalent.

Python tuples can be created using only a comma ,with parentheses as a useful way to distinguish between them.

For example, note:

>>> x = 1,2,3
>>> print x, type(x)
(1, 2, 3) <type 'tuple'>

>>> x = (1)
>>> print x, type(x)
1 <type 'int'>

>>> x = 1,
>>> print x, type(x)
(1,) <type 'tuple'>

>>> x = (1,)
>>> print x, type(x)
(1,) <type 'tuple'>

, .

, .

, , :

latitude, longitude = (23.000, -10.993)

:

latitude, longitude = geo-point # Where geo point is (23.3,38.3) or [12.2,83.33]

, , :

first_name, last_name, address, date_of_birth, favourite_icecream = ... # you get the idea.
+7

Source: https://habr.com/ru/post/1584821/


All Articles