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 ?

AVANISH RAJBHAR
  • 527
  • 3
  • 9
laxman
  • 1,781
  • 4
  • 14
  • 32
  • To consider a single element as a tuple but not as just an element, you need a comma at the end. – shaik moeed Feb 25 '20 at 06:45
  • Simply because `('hello')` wouldn't be a tuple. – Klaus D. Feb 25 '20 at 06:46
  • 1
    Does this answer your question? [What is the syntax rule for having trailing commas in tuple definitions?](https://stackoverflow.com/questions/7992559/what-is-the-syntax-rule-for-having-trailing-commas-in-tuple-definitions) – Wouterr Feb 25 '20 at 06: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 – laxman Feb 25 '20 at 06:50
  • @Wouterr, the question is closely related but I am more concerned about reasoning as of why the printing of tuple is inconsistent. – laxman Feb 25 '20 at 06:57

2 Answers2

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 ,.

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
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

Tony
  • 1