1

I had introduced a bug in a script of mine by putting a comma after a function call. Here I will illustrate with a silly example:

def uppered(my_string):
    return my_string.upper()

foo = uppered("foo")
print(foo)

This returns, as expected, a string:

FOO

However, if I change the script so that I call the function with a comma appended after the function call, like this:

foo = uppered("foo"),

Then I get a tuple back (!):

('FOO',)

This seems so weird to me - I would have expected the interpreter to return a SyntaxError (as it does if I have two commas instead of one). Can someone please enlighten me what the logic is here and where to find more information on this behavior. My google-fu let me down on this very specific detail.

jockster
  • 397
  • 1
  • 3
  • 10

4 Answers4

2

Because you have created a tuple.

foo = uppered("foo"), 

Is equivalent to:

foo = (uppered("foo"),)

Which creates a single-elemnt tuple, obviously equivalent to

foo = ('FOO',)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

Tuples in Python can be written as:

my_tuple = ()

or:

my_tuple = (1, 2)

or:

my_tuple = 1, 2

Don't believe me? Well:

>>> my_tuple = 1,
>>> my_tuple
(1,)
Huy Vo
  • 2,418
  • 6
  • 22
  • 43
0

Well, it's how Python syntax works. A single comma after a value will turn create a tuple with this value as the first and only element. See answers for this question for a broader discussion.

Imagine there is an omitted pair of parentheses:

foo = (uppered("foo"),)

Why so? It to write like this:

stuff = foo(), bar(), baz()
# More code here
for thing in stuff:

You could've used a pair of parentheses (and you do need them in other languages), but aesthetics of Python require syntax to be as short and clear as possible. Commas are necessary as separators, but parentheses really aren't. Everything between the beginning side of expression and the end of the line (or :, or closing parentheses/brackets in case of generators or comprehensions) is to be elements of the created tuple. For one element tuple, this syntax should be read as "a tuple of this thing and nothing more", because there is nothing between comma and end of the line.

Community
  • 1
  • 1
Synedraacus
  • 975
  • 1
  • 8
  • 21
0

You can use .join() function. It returns string concatenated with elements of tuple.

g = tuple('FOO')
k = ''
K = k.join(g)
print(K)
print(type(K))

FOO

class 'str'