Are there more ways to define a tuple with only one item?
I know this is one way, by placing a comma:
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>&g开发者_开发问答t; len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Source: http://docs.python.org/tutorial/datastructures.html
Are there more ways to define a tuple with only 1 item?
>>> tuple(['hello'])
('hello',)
But the built-in syntax is there for a reason.
Even though you can define a tuple as 'hello',
I think it would be easy for someone to possibly miss the trailing comma if they were reading your code. I definitely prefer
('hello',)
from a readability stand-point.
singleton = ('hello',)
This is more clear I guess, and @jleedev even more clear. But I like the method you used the best:
singleton = 'hello',
Another one is
>>> (1, 2)[0:1]
(1,)
A very obfuscated way, but it is an alternative...
精彩评论