benni
benni

Reputation: 673

What does ,= mean in python?

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

Example from matplotlib:

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

Upvotes: 36

Views: 3516

Answers (3)

shuttle87
shuttle87

Reputation: 15954

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

Upvotes: 17

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33096

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.

Upvotes: 43

Mureinik
Mureinik

Reputation: 312136

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-').

Upvotes: 2

Related Questions