0

This seems a trivial questions, but I could not find the answer anywhere.

When working with lines in mathplotlib, all the tutorials I have seen inicialize the line variable followed by a comma ,. Example:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
line, = ax.plot(x, y, color='k')

for n in range(len(x)):
    line.set_data(x[:n], y[:n])
    ax.axis([0, 10, 0, 1])
    fig.canvas.draw()
    fig.savefig('Frame%03d.png' %n)

Here is another example using a different method.

line, = plt.plot(x, y, '-')

Why do I need this comma ,? Could I pass another variable after the comma? Does this methods return a tuple? If so, what exactly is being returned?

Some of my graphs seem to work when I don't put the comma, so why do all tutorials have this comma after the variable line?

edit: It has been pointed out that the method returns a tuple with one element (x, = ... - is this trailing comma the comma operator?), but if this is the case, why not just simply returning the element? Is there a practical use to the tuple? Is there situations where it returns a tuple with more than 1 element?

user3347814
  • 1,138
  • 9
  • 28
  • 50
  • 3
    Does this answer your question? https://stackoverflow.com/questions/16037494/x-is-this-trailing-comma-the-comma-operator – gmdev Oct 08 '20 at 13:57
  • Ok. the method returns a tuple with 1 element, but if this is the case, why not just simply returning the element? Is there a practical use to the tuple? Is there situations where it returns a tuple with more than 1 element? – user3347814 Oct 08 '20 at 14:32
  • 1
    I believe (someone correct me if I am wrong), that the comma is simply just syntax for unpacking tuples containing zero or one items. If you do not include the comma, you would have to write `line[0]` instead of just `line` every time you want to do an operation on it. This is because `ax.plot()` returns a list of `matplotlib`'s `Line2D` object. You can read more about `ax.plot` here: https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html – gmdev Oct 08 '20 at 14:57
  • 1
    For a very simple and basic explanation, you can also view the second answer at this link: https://stackoverflow.com/questions/16037494/x-is-this-trailing-comma-the-comma-operator – gmdev Oct 08 '20 at 14:59

0 Answers0