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
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
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
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
a, b and
(a, b) specify a tuple, and you need a tuple in the LHS (left hand side) for tuple unpacking 🙂
yes, and it works also on list
>>> x,y,z = range(3) >>> print x, y, z 0 1 2 >>>
There’s no difference.