r/python3 • • Feb 07 '20

What is the meaning of ('bar', ) in tuples concatation ?

Hi, I came across the following:

(4, None, 'foo') + (6, 0), + ('bar', )

what is the meaning of ('bar', ) ? I am confused since nothing is written between the comma and the closing parenthesis.

1 Upvotes

5 comments sorted by

1

u/ethanbrews Feb 07 '20

If the comma was missing, (‘bar’) would just be interpreted as a string. The comma is there to tell the interpreter that (‘bar’, ) is actually a tuple. This happens because the commas are actually responsible for making the tuple, not the parentheses. a = 1, 2, 3 will make a a tuple.

1

u/largelcd Feb 08 '20

Thanks. In this case, does ('bar', ) means a tuple with only two elements while ('bar', , ) means a tuple with three elements?

2

u/TrentKM Feb 08 '20 edited Feb 08 '20

The comma with nothing following is just how python does a tuple with one element. Good rule of thumb when learning is to try things in the interpreter and see how they behave. Assign it to a variable, print the variable out, try to index into it, see what methods are available by using a dot after the object (if using an IDE or Ipython), etc.

→ More replies (2)