开发者

Are there more ways to define a tuple with only one item?

开发者 https://www.devze.com 2022-12-20 05:52 出处:网络
I know this is one way, by placing a comma: >>> empty = () >>> singleton = \'hello\',# <-- note trailing comma

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

0

精彩评论

暂无评论...
验证码 换一张
取 消