Use parentheses or not for multiple variable assignment in Python?
Asked Answered
G

1

7

I've come across these variations when seeing multiple variables getting assigned at once:

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 these and they all seem to assign the same values and I checked the variable types and they seem to all be ints.

So are these all truly equivalent or is there something subtle I'm missing? If they are equivalent, which is considered proper in Python?

Guenevere answered 27/4, 2015 at 3:45 Comment(1)
@Mark Dickinson: well it depends on semantics; if x,y,x are for example coordinates of a point in space (they are a tuple in the context of the application) it can actually make more sense to assign them as a tuple since in python this is possible instead of assigning each value independently. The result is the same but using a tuple the python syntax reflects the meaning of the three values as a tuple at application levelLunulate
S
15

As you've noted, they are all functionally equivalent.

Python tuples can be created using just a comma ,, with parentheses as a useful way to delineate 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'>

When you are doing multiple assignment, the parentheses again just define precedence.

As for which is best, it depends on your case.

This is probably ok:

latitude, longitude = (23.000, -10.993)

This is too:

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

This is probably overkill:

first_name, last_name, address, date_of_birth, favourite_icecream = ... # you get the idea.
Sandoval answered 27/4, 2015 at 4:15 Comment(1)
Thank you, especially for clarifying the role of the comma.Guenevere

© 2022 - 2024 — McMap. All rights reserved.