python元组为什么只有一个元素要加逗号,为什么在元组设计中python为什么选择逗号而不是括号?...

Multiple Element Tuples

In Python, multiple-element tuples look like:

1,2,3

...

but again, it is the commas, not the parentheses, that define the tuple.

Oh, really?!

Then why:

>>> tuple((((((1, 2, 3)))))) # creates a valid tuple

# (1, 2, 3)

>>> tuple(1, 2, 3, ) # But not here

# TypeError: tuple() takes at most 1 argument (3 given)

More seriously, I don't get why the parenthesis was not chosen over the commas?

Because I think it would create a paradox when:

>>> 1, # is a valid tuple

# (1,)

>>> tuple([1]) # Or this

# (1,)

>>> tuple(1) # But not this one

# TypeError: 'int' object is not iterable

However, if you consider that parenthesis were always in charge of instantiating a tuple, all of the problems with instantiating tuple with multiple items are gone.

e.g. in my imaginary world:

>>> (1, 2, 3) # stay valid

# (1, 2, 3)

>>> (1) # is newly valid

# (1)

>>> () # stay valid

# ()

>>> 1,

# TypeError: int() takes exactly 1 argument (2 given)

I know this is a well-known feature and I'm already sorry if it a duplicate. I have found lots of similar topics about how tuple worked, but none explaining in details why this feature was created like that.

I am also aware that this topic could be closed as opinion-based, but I am mostly interested in technical reasons (if any), or at least historical reasons.

Thank you

解决方案

This is an artifact of the grammar.

The terms separated by commas are a building block for tuples, lists, and sets depending on whether they are wrapped by square brackets, curly braces, or nothing at all.

The chief challenge when specifying a grammar is balancing multiple competing uses of the same characters. Commas separate parts of lists, tuples, dicts, and sets. Commas also separate arguments in function calls. Trailing commas are allowed for both uses (and are required for tuples of length one). Likewise, parentheses have multiple uses including function calls and grouping for arithmetic expressions. The period serves as a decimal point and for the getattribute operator.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值