Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x, = ... - is this trailing comma the comma operator?

People also ask

What is a trailing comma?

A trailing comma, also known as a dangling or terminal comma, is a comma symbol that is typed after the last item of a list of elements. Since the introduction of the JavaScript language, trailing commas have been legal in array literals. Later, object literals joined arrays.

Can I use trailing comma?

Trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to JavaScript code. If you want to add a new property, you can add a new line without modifying the previously last line if that line already uses a trailing comma.

What is the comma after a variable Python?

I was going to say that it's comma separated variable assignment, but it's called “tuple assignment”. This means the function returns multiple variables, that happens in the form of a tuple. Using multiple variables separated by a comma unpacks the tuple return into the variables.

What is a trailing comma in Python?

Trailing commas refers to a comma at the end of a series of values in an array or array like object, leaving an essentially empty slot. e.g., [1, 2, 3, ] I kind of like them when I work on Ruby and Python projects.


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.


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]