Reputation: 2110
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 ?
Upvotes: 2
Views: 72
Reputation: 15872
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 ,
.
Upvotes: 4
Reputation: 1
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
Upvotes: 0