truth1ness
truth1ness

Reputation: 5041

Use parentheses or not for multiple variable assignment in Python?

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?

Upvotes: 7

Views: 6641

Answers (1)

user764357
user764357

Reputation:

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.

Upvotes: 15

Related Questions