Python 中具有單個元素的元組需要尾隨逗號

商業

元組,在 Python 中是不可變(不可更改)的序列對象。

生成具有單個元素或空元組的元組時必須小心。

此處描述了以下詳細信息。

  • 具有 1 個元素的元組
  • 元組圓括號可以省略。
  • 空元組
  • 函數參數中的元組

具有 1 個元素的元組

如果您嘗試生成一個包含一個元素的元組並且只在圓括號 () 內寫入一個對象,則圓括號 () 將被忽略和處理,並且不會被視為元組。

single_tuple_error = (0)

print(single_tuple_error)
print(type(single_tuple_error))
# 0
# <class 'int'>

需要尾隨逗號來生成具有一個元素的元組。

single_tuple = (0, )

print(single_tuple)
print(type(single_tuple))
# (0,)
# <class 'tuple'>

例如,當使用 + 運算符連接多個元組時,請注意,如果嘗試添加一個元素而忘記了逗號,則會出錯。

# print((0, 1, 2) + (3))
# TypeError: can only concatenate tuple (not "int") to tuple

print((0, 1, 2) + (3, ))
# (0, 1, 2, 3)

元組圓括號可以省略。

一個元素的元組之所以需要逗號,是因為元組不是用圓括號 () 括起來的值,而是用逗號分隔的值。

創建元組的是逗號,而不是圓括號。
Tuples — Built-in Types — Python 3.10.4 Documentation

即使省略了圓括號 (),它也被作為一個元組處理。

t = 0, 1, 2

print(t)
print(type(t))
# (0, 1, 2)
# <class 'tuple'>

請注意,對像後面的不必要逗號被視為元組。

t_ = 0,

print(t_)
print(type(t_))
# (0,)
# <class 'tuple'>

空元組

如上所述,圓括號 () 在表示元組時可以省略,但在生成空元組時是必需的。

單獨的空格或逗號將導致 SyntaxError。

empty_tuple = ()

print(empty_tuple)
print(type(empty_tuple))
# ()
# <class 'tuple'>

# empty_tuple_error = 
# SyntaxError: invalid syntax

# empty_tuple_error = ,
# SyntaxError: invalid syntax

# empty_tuple_error = (,)
# SyntaxError: invalid syntax

空元組也可以由不帶參數的 tuple() 生成。

empty_tuple = tuple()

print(empty_tuple)
print(type(empty_tuple))
# ()
# <class 'tuple'>

函數參數中的元組

即使存在語法歧義,也需要元組圓括號 ()。

函數參數用逗號分隔,但在這種情況下,有必要通過圓括號 () 的存在與否來明確指示函數是否為元組。

沒有括號 (),每個值都被傳遞給每個參數;使用括號 (),每個值都作為一個元組傳遞給一個參數。

def example(a, b):
    print(a, type(a))
    print(b, type(b))

example(0, 1)
# 0 <class 'int'>
# 1 <class 'int'>

# example((0, 1))
# TypeError: example() missing 1 required positional argument: 'b'

example((0, 1), 2)
# (0, 1) <class 'tuple'>
# 2 <class 'int'>

如果元組標有星號 *,則元組的元素可以擴展並作為參數傳遞。

example(*(0, 1))
# 0 <class 'int'>
# 1 <class 'int'>

有關詳細信息,請參閱以下文章。