64

I don't understand what does comma after variable lines, means: http://matplotlib.org/examples/animation/simple_anim.html

line, = ax.plot(x, np.sin(x))

If I remove comma and variable "line," becomes variable "line" then program is broken. Full code from url given above:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.arange(0, 2*np.pi, 0.01)        # x-array
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x+i/10.0))  # update the data
    return line,

#Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
    interval=25, blit=True)
plt.show()

According to http://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences comma after variable seems to be related to tuples containing only one item.

miradulo
  • 28,857
  • 6
  • 80
  • 93
inzzz
  • 885
  • 1
  • 10
  • 13
  • 1
    Your last line hits the nail on the head. What it assumes you already know is that when you do an assignment between iterables the elements are lined up. So `x,y,z=1,2,3` is a Pythonic way of writing `x=1;y=2;z=3`. – kojiro Apr 16 '13 at 12:55
  • 2
    I can't add more to the answer below, but I thought I'd add a neat result: the comma operator also gives Python the ability to switch variable values in one expressive, clear line (saw this in The Quick Python Book): `x2,x1 = x1,x2`. – Ahmed Nov 24 '15 at 10:25

2 Answers2

81

ax.plot() returns a tuple with one element. By adding the comma to the assignment target list, you ask Python to unpack the return value and assign it to each variable named to the left in turn.

Most often, you see this being applied for functions with more than one return value:

base, ext = os.path.splitext(filename)

The left-hand side can, however, contain any number of elements, and provided it is a tuple or list of variables the unpacking will take place.

In Python, it's the comma that makes something a tuple:

>>> 1
1
>>> 1,
(1,)

The parenthesis are optional in most locations. You could rewrite the original code with parenthesis without changing the meaning:

(line,) = ax.plot(x, np.sin(x))

Or you could use list syntax too:

[line] = ax.plot(x, np.sin(x))

Or, you could recast it to lines that do not use tuple unpacking:

line = ax.plot(x, np.sin(x))[0]

or

lines = ax.plot(x, np.sin(x))

def animate(i):
    lines[0].set_ydata(np.sin(x+i/10.0))  # update the data
    return lines

#Init only required for blitting to give a clean slate.
def init():
    lines[0].set_ydata(np.ma.array(x, mask=True))
    return lines

For full details on how assignments work with respect to unpacking, see the Assignment Statements documentation.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 4
    Yep. If it helps, you can think of it as being equivalent to `line = ax.plot(x, np.sin(x))[0]` – Aya Apr 16 '13 at 12:51
  • 2
    @Aya: except the `line, = ...` syntax will throw an exception when the right-hand side has 0 or more than 1 element in the iterable, while using indexing will only throw an exception if there are 0 elements. – Martijn Pieters Mar 10 '17 at 22:03
  • about once a year I break up a line and miss a trailing comma at the end of the line like `x = 1,`. Then it takes a while before I finally realize why tuples are appearing somewhere they're not supposed to be – Joseph Sheedy Aug 16 '19 at 22:33
  • 1
    Note that `plt.plot` allows many ways for its parameters. E.g. `plot(x1, y1, 'g^', x2, y2, 'g-')` will return a list with two `Line2D` elements. For consistency, also when there is only one `Line2D` element a list will be returned. – JohanC Oct 08 '20 at 14:11
28

If you have

x, = y

you unpack a list or tuple of length one. e.g.

x, = [1]

will result in x == 1, while

x = [1]

gives x == [1]

Elmar Peise
  • 14,014
  • 3
  • 21
  • 40