Python 元組 tuple() 方法



Python 元組 tuple() 方法用於將專案列表轉換為元組。

元組是 Python 物件的集合,這些物件以逗號分隔,是有序且不可變的。元組是序列,就像列表一樣。元組和列表的區別在於:元組不能像列表那樣更改,元組使用括號,而列表使用方括號。

語法

以下是 Python 元組 tuple() 方法的語法:

tuple(seq)

引數

  • seq − 這是要轉換為元組的序列。

返回值

此方法返回該元組。

示例

以下示例顯示了 Python 元組 tuple() 方法的用法。這裡建立一個包含字串作為元素的列表 'aList'。然後使用 tuple() 方法將此列表轉換為元組。

aList = ['xyz', 'zara', 'abc']
aTuple = tuple(aList)
print ("Tuple elements : ", aTuple)

執行上述程式時,會產生以下結果:

Tuple elements :  ('xyz', 'zara', 'abc')

示例

在這裡,我們建立一個字典 'dict1'。然後將此字典作為引數傳遞給 tuple() 方法。之後,我們檢索字典的元組。

# iterable dictionary
dict1 = {'Name': 'Rahul', 'Hobby': 'Singing', 'RollNo': 45}
# using tuple() method
res = tuple(dict1)
# printing the result
print("dictionary to tuple:", res)

執行上述程式碼時,我們得到以下輸出:

dictionary to tuple: ('Name', 'Hobby', 'RollNo')

示例

現在,我們將建立一個字串。然後將此字串作為引數傳遞給 tuple() 方法。之後,我們檢索字串的元組。

# iterable string
string = "Tutorials Point";
# using tuple() method
res = tuple(string)
# printing the result
print("converted string to tuple:", res)

以下是上述程式碼的輸出:

converted string to tuple: ('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', ' ', 'P', 'o', 'i', 'n', 't')

示例

如果傳遞空元組,tuple() 方法不會引發任何錯誤。它返回一個空元組。

# empty tuple
tup = tuple()
print("Output:", tup)

上述程式碼的輸出如下:

empty tuple: ()

示例

如果未傳遞可迭代物件,則 tuple() 方法會引發 TypeError。以下程式碼對此進行了說明。

#a non-iterable is passed as an argument
tup = tuple(87)
# printing the result
print('Output:', tup)

我們得到上述程式碼的輸出,如下所示:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 2, in <module>
    tup = tuple(87)
TypeError: 'int' object is not iterable
python_tuples.htm
廣告