2

I have just started to learn python and following the docs on tuples, I came across this snippet,

>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) 

Following this I ran following snippet,

>>> foo=1,2,3, >>> len(foo) 3 >>> foo (1, 2, 3) 

Why does singleton prints with an trailing comma , where as foo seems to trim it ?

5
  • To consider a single element as a tuple but not as just an element, you need a comma at the end. Commented Feb 25, 2020 at 6:45
  • Simply because ('hello') wouldn't be a tuple. Commented Feb 25, 2020 at 6:46
  • 1
    Does this answer your question? What is the syntax rule for having trailing commas in tuple definitions? Commented Feb 25, 2020 at 6:50
  • yes that I understand but shouldn't the python interpreter should automatically trim the trailing comma and print ('hello'), since enclosing parenthesis are enough to determine that its a tuple, not a string otherwise Commented Feb 25, 2020 at 6:50
  • @Wouterr, the question is closely related but I am more concerned about reasoning as of why the printing of tuple is inconsistent. Commented Feb 25, 2020 at 6:57

2 Answers 2

4

Beacause ("Hello") is not a tuple, it is same as "Hello".

>>> ("Hello") 'Hello' 

in order to distinguish tuple with single element from a simple expression in () a , is necessary. Whereas (1,2,3) is clearly a collection of items, and as they are enclosed by () it can easily be inferred as a tuple, hence no need for a trailing ,.

Sign up to request clarification or add additional context in comments.

Comments

0

because you define variable"singleton" as ("hello",), you don't need comma to end it, and for "foo", you define it, so it shows as what you defined

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.