Why single element tuple is interpreted as that element in python?

前端 未结 5 1503
[愿得一人]
[愿得一人] 2020-12-04 02:44

Could anyone explain why single element tuple is interpreted as that element in Python?

And

Why don\'t they just print the tuple (1,) as (

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 03:22

    A single element tuple is never treated as the contained element. Parentheses are mostly useful for grouping, not for creating tuples; a comma does that.

    Why don't they just print (1,) as (1)?

    Probably because printing a builtin container type gives a representation that can be used to recreate the container object via , say eval:

    The docs for __repr__ provides some clarity on this:

    If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value

    Answering your question, (1) is just integer 1 with a grouping parenthesis. In order to recreate the singleton tuple via its representation, it has to be printed as (1,) which is the valid syntax for creating the tuple.

    >>> t = '(1,)'
    >>> i = '(1)'
    >>> eval(t)
    (1,) # tuple
    >>> eval(i)
    1    # int
    

提交回复
热议问题