Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x,y = getPos() vs. (x, y) = getPos()

Tags:

python

tuples

Consider this function getPos() which returns a tuple. What is the difference between the two following assignments? Somewhere I saw an example where the first assignment was used but when I just tried the second one, I was surprised it also worked. So, is there really a difference, or does Python just figure out that the left-hand part should be a tuple?

def getPos():
  return (1, 1)

(x, y) = getPos() # First assignment
x, y   = getPos() # Second assignment
like image 897
helpermethod Avatar asked Oct 15 '10 10:10

helpermethod


5 Answers

Read about tuples:

A tuple consists of a number of values separated by commas (...)

So parenthesis does not make a tuple a tuple. The commas do it.

Parenthesis are only needed if you have weird nested structures:

x, (y, (w, z)), r
like image 102
Felix Kling Avatar answered Oct 18 '22 10:10

Felix Kling


Yes, it's called tuple unpacking:

"Tuple unpacking requires that the list of variables on the left has the same number of elements as the length of the tuple." - Guido Van Rossum

"When you use tuples or lists on the left side of the =, Python pairs objects on the right side with targets on the left and assigns them from left to right." - Lutz and Ascher

like image 21
Skilldrick Avatar answered Oct 18 '22 11:10

Skilldrick


There is no difference:

>>> import dis
>>> dis.dis(compile("a,b = expr()", "", "single"))
  1           0 LOAD_NAME                0 (expr)
              3 CALL_FUNCTION            0
              6 UNPACK_SEQUENCE          2
              9 STORE_NAME               1 (a)
             12 STORE_NAME               2 (b)
             15 LOAD_CONST               0 (None)
             18 RETURN_VALUE        
>>> dis.dis(compile("(a,b) = expr()", "", "single"))
  1           0 LOAD_NAME                0 (expr)
              3 CALL_FUNCTION            0
              6 UNPACK_SEQUENCE          2
              9 STORE_NAME               1 (a)
             12 STORE_NAME               2 (b)
             15 LOAD_CONST               0 (None)
             18 RETURN_VALUE        

Both a, b and (a, b) specify a tuple, and you need a tuple in the LHS (left hand side) for tuple unpacking :)

like image 4
tzot Avatar answered Oct 18 '22 10:10

tzot


yes, and it works also on list

>>> x,y,z = range(3)
>>> print x, y, z
0 1 2
>>> 
like image 3
Ant Avatar answered Oct 18 '22 10:10

Ant


There's no difference.

like image 1
fortran Avatar answered Oct 18 '22 11:10

fortran