Python tuple() 函式



Python 的tuple()函式用於建立元組,元組是一個有序且不可變(不可更改)元素的集合。此集合可以包含各種資料型別,例如數字、字串,甚至其他元組。

元組類似於列表,但主要區別在於,一旦建立了元組,就不能修改其元素,即不能新增、刪除或更改它們。

語法

以下是 Python tuple() 函式的語法:

tuple(iterable)

引數

此函式接受任何可迭代物件作為引數,例如列表、字串、集合或另一個元組。

返回值

此函式返回一個新的元組物件,其中包含給定可迭代物件中的元素。

示例 1

在以下示例中,我們使用 tuple() 函式將列表“[1, 2, 3]”轉換為元組:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print('The tuple object obtained is:',my_tuple)

輸出

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

The tuple object obtained is: (1, 2, 3)

示例 2

在這裡,我們使用 tuple() 函式將字串“Python”轉換為其各個字元的元組:

my_string = "Python"
char_tuple = tuple(my_string)
print('The tuple object obtained is:',char_tuple)

輸出

上述程式碼的輸出如下:

The tuple object obtained is: ('P', 'y', 't', 'h', 'o', 'n')

示例 3

在這裡,我們使用 tuple() 函式而不帶任何引數,建立一個空元組(()):

empty_tuple = tuple()
print('The tuple object obtained is:',empty_tuple)

輸出

獲得的結果如下所示:

The tuple object obtained is: ()

示例 4

在本例中,我們將集合“{4, 5, 6}”的元素轉換為元組:

my_set = {4, 5, 6}
set_tuple = tuple(my_set)
print('The tuple object obtained is:',set_tuple)

輸出

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

The tuple object obtained is: (4, 5, 6)

示例 5

在此示例中,我們使用 tuple() 函式對巢狀列表“[[1, 2], [3, 4]]”,建立一個包含巢狀元組的元組:

nested_list = [[1, 2], [3, 4]]
nested_tuple = tuple(nested_list)
print('The tuple object obtained is:',nested_tuple)

輸出

產生的結果如下:

The tuple object obtained is: ([1, 2], [3, 4])
python_type_casting.htm
廣告