views:

83

answers:

4

I know this is one way, by placing a comma:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> 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?

+5  A: 
>>> tuple(['hello'])
('hello',)

But the built-in syntax is there for a reason.

jleedev
The first version is much clearer, IMO.
Edan Maor
@Edan: Less code using the built-in, but the trailing comma doesn't really jump out an say "TUPLE!"... my eyes might miss it.
jcoon
Singleton tuples are something of a curiosity, to be sure. Here's GVR's justification for their existence: http://www.python.org/search/hypermail/python-1992/0292.html
jleedev
+1  A: 

singleton = ('hello',)

This is more clear I guess, and @jleedev even more clear. But I like the method you used the best:

singleton = 'hello',

jcoon
+1  A: 

Another one is

>>> (1, 2)[0:1]
(1,)

A very obfuscated way, but it is an alternative...

jae
+3  A: 

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.

awesomo