1

In animate_decay.py of matplotlib examples, return statement is used with a trailing comma as in:

return line,

and the function is a normal function and is not a generator function.

So, I have written two versions of the same function, one with a trailing comma and another without one:

def no_trailing_comma(x):
  return x + [10]

def trailing_comma(x):
  return x + [10],

data = [1, 2, 3]

print("With trailing comma", trailing_comma(data))
print("With no trailing comma", no_trailing_comma(data))

In either case, the output was the same:

With trailing comma [1, 2, 3, 10]

With no trailing comma [1, 2, 3, 10]

The language specification (Python 3.6) does not make any special mention on trailing commas in return statements. Am I missing something?

Seshadri R
  • 1,192
  • 14
  • 24
  • 5
    [That's not the output I see.](http://ideone.com/vFimD6) – user2357112 Jul 21 '17 at 03:56
  • @user2357112 Strange. You have used Python 3.5 and I am using 3.6. I swear by my output (and you will, by yours). – Seshadri R Jul 21 '17 at 04:03
  • `,` in this context is a [`tuple`](https://docs.python.org/3.6/library/stdtypes.html?highlight=tuple#tuple) literal, in particular a tuple with a single value (I'm running 3.6 and like 2.6, 2.7, 3.5 etc. it results in `([1, 2, 3, 10],)` - a tuple with one value. – AChampion Jul 21 '17 at 04:04
  • Trying it on 3.6 still produces a tuple with the trailing comma. – user2357112 Jul 21 '17 at 04:08

1 Answers1

14

Basically putting a comma after the return statement casts the parameter that you are returning to a tuple containing the parameter. It won't affect the value of the parameter at all, but rather how it is packaged. Using your example functions

def no_trailing_comma(x):
  return x + [10]

def trailing_comma(x):
  return x + [10],

data = [1, 2, 3]

no_comma_value = no_trailing_comma(data)
comma_value = trailing_comma(data)

print("The return type is", type(no_comma_value))
print("The return type is", type(comma_value))

This code would yield:

The return type is <class 'list'>

The return type is <class 'tuple'>

You should have seen a difference in the print outputs (i.e. one being in a tuple) but this could be a 3.6 thing that I don't know about yet.

JBuete
  • 394
  • 2
  • 4
  • One minor nit, it doesn't cast it to a `tuple` it is a `tuple` literal. Just like you wouldn't say `[1]` is casting to a `list`. A trailing `,` is just a `tuple` literal of one value. – AChampion Jul 21 '17 at 05:41