2

I am wondering what the comma does in this code:

line, =

The following example shows the behavior:

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
print("First:")
print(line)
print("Second:")
line = ax.plot([], [], lw=2)
print(line)

Result:

First:
Line2D(_line0)
Second:
[<matplotlib.lines.Line2D object at 0xb137c4c>]

It really becomes confusing when I try to use the line variable, and I don't know whether to use the trailing comma or not:

def init():
    line.set_data([], [])
    return line,

Or is there a better way to do this which avoids the comma?

Anonymous
  • 11,748
  • 6
  • 35
  • 57
DrJay
  • 123
  • 6
  • This is useful when you have a container with a single item, instead of `x = L[0]`, you can just do `x, = L` – jamylak Apr 19 '13 at 10:04

4 Answers4

6

It's just unpacking a 1-tuple. eg:

line, = ('foo',)   # same as line = 'foo' in this example

compare with

line1, line2 = ('foo', 'bar') # unpack a 2-tuple

etc.

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
4

It's helpful for unpacking tuples

See the different results here:

a = (1,)
print(a) # prints (1,)

a,  = (1,)
print(a) # prints 1
aldeb
  • 6,588
  • 5
  • 25
  • 48
1

In Python, there's a short-hand to assign multiple variables at once:

(a, b, c) = something

You assign to a tuple of variables instead of a single variable. This example will raise an exception if something isn't a collection with exactly 3 elements; otherwise it will bind a to the first item in something, b to the second, and c to the third.

As you may know, in Python tuples the parentheses are usually optional; it's the commas that are important. So you could also write my example as:

a, b, c = something

And this of course works for any size tuple of variables, not just three. And 1-tuples are represented by having a single item with a tailing comma and nothing following1. So your example:

line, = ax.plot([], [], lw=2)

Is just asserting that ax.plot([], [], lw=2) returns a collection with a single element, and binding line to that element. It differs form the nearly identical statement:

line = ax.plot([], [], lw=2)

because that would bind line to the collection itself, and contains no assertion about the number of elements it has.


1 This is a little ugly, but necessary because the only other obvious syntax would be (item), which would clash with the syntax for simply parenthesising a sub-expression. E.g. nobody wants 2 * (3 + 1) to give an error about multiplying an int and a tuple.

Ben
  • 68,572
  • 20
  • 126
  • 174
0

It makes the variable the first (and in this case only) item in a tuple. This allows 'multuple' assignment such as:

a, b = 1, 2

This is particularly useful for swapping values so, carrying on from the above, you could do:

a, b = b, a

And the a and b variable would swap values.

cms_mgr
  • 1,977
  • 2
  • 17
  • 31