What does ,= mean in python?

Question:

I wonder what ,= or , = means in python?

Example from matplotlib:

plot1, = ax01.plot(t,yp1,'b-')
Asked By: benni

||

Answers:

It’s a form of tuple unpacking. With parentheses:

(plot1,) = ax01.plot(t,yp1,'b-')

ax01.plot() returns a tuple containing one element, and this element is assigned to plot1. Without that comma (and possibly the parentheses), plot1 would have been assigned the whole tuple. Observe the difference between a and b in the following example:

>>> def foo():
...     return (1,)
... 
>>> (a,) = foo()
>>> b = foo()
>>> a
1
>>> b
(1,)

You can omit the parentheses both in (a,) and (1,), I left them for the sake of clarity.

Answered By: Stefano Sanfilippo

Adding a , after a variable places it in a tuple with a single element. This tuple is then assigned a value (with the = operator) returned from ax01.plot(t,yp1,'b-').

Answered By: Mureinik

Python allows you to put tuples on the left hand side of the assignment.
The code in the question is an example of this, it might look like it’s a special case of an operator but it’s really just a case tuple assignment going on here. Some examples might help:

a, b = (1, 2)

which gives you a = 1 and b = 2.

Now there’s the concept of the one element tuple as well.

x = (3,)

gives you x = (3,) which is a tuple with one element, the syntax looks a bit strange but Python needs to differentiate from plain parenthesis so it has the trailing comma for this (For example z=(4) makes z be the integer value 4, not a tuple). If you wanted to now extract that element then you would want to use something like you have in the question:

y, = x

now y is 3. Note that this is just tuple assignment here, the syntax just appears a bit strange because it is tuple of length one.

See this script for an example: http://ideone.com/qroNcx

Answered By: shuttle87
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.