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.

Answer from Martijn Pieters on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ need help adding a comma after a variable
r/learnpython on Reddit: Need help adding a comma after a variable
June 3, 2020 -

Noob here

if I had this as my code...

print('The',highway_number,'is auxiliary, serving the',highway_two_digits,", going", end = ' ')

how would I add a comma after the varible highway_two_digits so that it said

The 405 is auxiliary, serving the 5, going north/south.

I can put a comma in, put i'm not sure how to make it so that it is directly after the variable rather than a space in between the variable and the comma.

sorry if this is confusing because it is for me too lol

๐ŸŒ
Quora
quora.com โ€บ How-does-Pythons-comma-operator-work-in-assignments-with-expressions
How does Python's comma operator work in assignments with expressions? - Quora
Answer (1 of 5): I assume you're referring to tuple assignment? How does Python's comma operator works during assignment?
๐ŸŒ
YouTube
youtube.com โ€บ watch
python: comma, = assignment! (beginner - intermediate) anthony explains #114 - YouTube
today I talk about the 1-ary unpacking assignment and an example and why it's useful!- variable unpackings: https://youtu.be/ObWh1AYClI0playlist: https://www...
Published ย  October 14, 2020
๐ŸŒ
Know Program
knowprogram.com โ€บ home โ€บ how to put a comma after a variable in python
How to Put a Comma After a Variable in Python - Know Program
January 24, 2023 - A for loop can be utilized to manually iterate through each character of the given string and add a comma after every single one of the characters. x = "Example" y = ' ' for i in x: y += i + ','*1 y = y.strip() print(repr(y)) ... The replace() ...
๐ŸŒ
YouTube
youtube.com โ€บ codesolve
python comma after variable - YouTube
Instantly Download or Run the code at https://codegive.com in python, the comma after a variable serves multiple purposes depending on the context in which ...
Published ย  March 29, 2024
Views ย  140
Find elsewhere
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ trailing-commas-in-python
The benefits of trailing commas - Python Morsels
January 10, 2025 - When I make a multi-line list, dictionary, tuple or function call (see wrap a long line in Python), I prefer to put the closing bracket or brace on its own line: fruits = [ "lemons", "pears", "jujubes", "apples", "bananas", "blueberries", "watermelon", ] I also usually prefer to put each element on its own line, with a comma after each one, including the last element.
๐ŸŒ
Quora
quora.com โ€บ What-does-the-comma-mean-in-Python
What does the comma mean in Python? - Quora
Answer (1 of 3): It can mean a number of things - but in all of them it is a separator between items : * A separator between parameters in a function definition: [code]def func(a,b,c,d): pass [/code] * A separator between base classes in a class definition [code]class Silly(Sillier, EvenSilli...
Top answer
1 of 2
18

What you describe is tuple assignment:

a, b = 0, 1

is equivalent to a = 0 and b = 1.

It can however have interesting effects if you for instance want to swap values. Like:

a,b = b,a

will first construct a tuple (b,a) and then untuple it and assign it to a and b. This is thus not equivalent to:

#not equal to
a = b
b = a

but to (using a temporary):

t = a
a = b
b = t

In general if you have a comma-separated list of variables left of the assignment operator and an expression that generates a tuple, the tuple is unpacked and stored in the values. So:

t = (1,'a',None)
a,b,c = t

will assign 1 to a, 'a' to b and None to c. Note that this is not syntactical sugar: the compiler does not look whether the number of variables on the left is the same as the length of the tuple on the right, so you can return tuples from functions, etc. and unpack them in separate variables.

2 of 2
1

For the purposes of reading, all it's doing is setting a and b, so that a = 0 and b = 1. Similarly, in line 7, it's setting a to b and b to the sum of a and b.

More specifically, it's setting tuples. Tuples are invariant, in that once they're created, their values can't change. Tuples are pervasive in python - you see them almost everywhere.

Typically, you would expect a tuple to be in parenthesis, e.g. (a, b) = (0, 1) would read more cleanly, but they are such a large feature of python that the parenthesis are optional (unless you're constructing a tuple as an argument to a function, and then you need the extra parenthesis to differentiate between a single tuple and multiple arguments. I.e. you would have to say foo((a, b)) to pass a tuple to foo, as foo(a, b) would pass two arguments to it.)

Tuples can be any length. You can write a, b, c, d, e = 0, 1, 2, 3, 4, or you can have a function return a tuple, e.g.: ret1, ret2, ret3 = foobar(1)

๐ŸŒ
Shallowsky
shallowsky.com โ€บ python โ€บ lesson1a.txt
Shallowsky
Larry asked if the second comma was to prevent printing a newline. Not in this case, but commas can do that if you put them at the *end* of the print statement. Like this: print "Hello,", name, Someone asked about double quotes vs. single quotes. In Python, you can use either type -- there's no difference.
๐ŸŒ
Deepnote
deepnote.com โ€บ app โ€บ sam-ola-ll โ€บ SamOlaModuleTwoLessonThreeActivityTwo-aa8a4436-05e4-483d-bb23-116c6ba643b5
Concept: Comma Print Formatting
November 10, 2023 - # review and run code number_errors = 0 print("An Integer of", 14, "combined with strings causes",number_errors,"TypeErrors in comma formatted print!")
Top answer
1 of 2
13

The problem is pretty straightforward, and your solution is as well. I have only a couple of small comments:

  1. The pop method in Python removes and returns the last item in a list, which can replace two lines.
  2. You don't have to new_string = '' when you set new_string on the next line. As a result, things can be shortened a bit.
  3. Personally, since str1 is only used once, I would personally just do it inline and not save it to a variable. The only time I save something to a variable, if it is only used once, is to shorten an otherwise-long line.
  4. Concatenating two hard-coded strings should be put in one operation (i.e. ' and' + ' ' => ' and '
  5. Guards! They're the best way to check input before executing.

My recommended version:

def items(some_list):
    if not some_list:
        return ''

    string_end = some_list.pop()
    if not some_list:
        return string_end

    and_display = ' and ' if len(some_list) == 1 else ', and '
    new_string = ', '.join(some_list) + and_display + string_end
    return new_string

print(items(['apples', 'kittens', 'tofu', 'puppies']))

This works fine as long as you are working with a list of strings. It will crash if you pass in an int or something that can't auto-convert to a string. That may or may not be a problem, depending on your perspective. Trying to make your code auto-convert things to strings, if they aren't strings, can be a very error-prone process. As a result, I think it is perfectly fine to write this the easy way, and let it be the developer's problem if it crashes due to non-string arguments.

Docstrings are usually helpful for this kind of thing.

Note on pass-by-reference

Hat tip to TheEspinosa: Python uses a pass-by-reference style for its arguments. As a result, modifying arguments (which is especially easy for lists, as is the case here) can result in unintentional side-effects. The use of pop (or del in your original code) results in the last entry being removed from the list, not just inside the function, but also in the variable passed in to the function. For your example usage, which calls this function with a constant value, this behavior doesn't matter. But it may as part of a larger application. There are three ways to handle this:

  1. Adjust your algorithm so you don't make any changes to any arguments being passed in (@Richard Nemann's answer works that way)
  2. Copy the list before using it inside your function. A simple shorthand to copy a list is: new_copy = old_copy[:]. There is also a copy module.
  3. Ignore it and let it be the caller's problem.

I use all three solutions depending on the circumstances or my mood. A copy operation obviously involves some overhead, but unless you know that performance is a problem, I would still do a copy if the algorithm that avoids the need for the copy is harder to understand.

To be clear about the problem the current code can potentially introduce, try running my implementation (or yours) like this:

vals = ['apples', 'bananas', 'grapes']
items(vals)
print(len(vals))

If you run this code the last line will print 2, because in your calling scope the variable has been modified-by-reference: grapes is no longer in the list.

I said at the beginning that this was a straightforward problem. At this point in time though I think it's fair to say that the devil is in the details :)

2 of 2
17

Your problem can be reduced to:

def list_english(items):
    """Returns a comma-separated string of the list's items,
    separating the last item with an 'and'.
    """
    if not items:
        return ''

    if len(items) == 1:
        return items[0]

    return '{}, and {}'.format(', '.join(items[:-1]), items[-1])

Note that variable and function names in python are to be named with underscore-separated lower-case according to PEP 8.
Also consider using docstrings to state, what a function's purpose is.

if __name__ == '__main__':
    print(list_english(['apples', 'kittens', 'tofu', 'puppies']))

Also enclose your script code in an if __name__ == '__main__': block to prevent it from being run if the module is solely imported.

Finally, consider your variable naming. Python has dynamic typing, so expressive names are especially important.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 51532179 โ€บ how-do-i-put-a-comma-next-to-a-variable
python - How do i put a comma next to a variable - Stack Overflow
It looks like you already have a comma next to a variable. ... When i run it, this is my answer: Enter your name: ian Hi ian , you have a short name. and i want to move the comma back one space ... Another option is to use the sep arg of print, eg print('Hi ', name, ', you have a short name.', sep=''). And in Python 3.6+ you can use an f-string to do the formatting: print(f'Hi {name}, you have a short name.').
๐ŸŒ
Python
peps.python.org โ€บ pep-0008
PEP 8 โ€“ Style Guide for Python Code | peps.python.org
When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line.