如何在Python元組中追加元素?


Python中的元組是不可變的,這意味著一旦建立,它們的內容就不能更改。但是,在某些情況下,我們希望更改現有的元組,在這種情況下,我們必須使用原始元組中更改後的元素建立一個新的元組。

以下是元組的示例:

s = (4,5,6) print(s) print(type(s))

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

(4, 5, 6)
<class 'tuple'>

元組是不可變的,儘管您可以使用 + 運算子連線多個元組。此時舊物件仍然存在,並且會建立一個新物件。

在元組中追加元素

元組是不可變的,儘管您可以使用 + 運算子連線多個元組。此時舊物件仍然存在,並且會建立一個新物件。

示例

以下是如何追加元組的示例:

s=(2,5,8) s_append = s + (8, 16, 67) print(s_append) print(s)

輸出

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

(2, 5, 8, 8, 16, 67)
(2, 5, 8)

注意:連線僅適用於元組。它不能與其他型別(例如列表)連線。

示例

以下是用列表連線元組的示例:

s=(2,5,8) s_append = (s + [8, 16, 67]) print(s_append) print(s)

輸出

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

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    s_append = (s + [8, 16, 67])
TypeError: can only concatenate tuple (not "list") to tuple

用一個元素連線元組

如果您想新增一個專案,您可以使用一個元素連線元組。

示例

以下是用一個元素連線元組的示例:

s=(2,5,8) s_append_one = s + (4,) print(s_append_one)

輸出

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

(2, 5, 8, 4)

注意:只有一個元素的元組的末尾必須包含逗號,如上述示例所示。

在元組中新增/插入專案

您可以透過在開頭或結尾新增新專案來連線元組,如前所述;但是,如果您希望在任何位置插入新專案,則必須將元組轉換為列表。

示例

以下是在元組中新增專案的示例:

s= (2,5,8) # Python conversion for list and tuple to one another x = list(s) print(x) print(type(x)) # Add items by using insert () x.insert(5, 90) print(x) # Use tuple to convert a list to a tuple (). s_insert = tuple(x) print(s_insert) print(type(s_insert))

輸出

我們得到上述程式碼的以下輸出。

[2, 5, 8]
⁢class 'list'>
[2, 5, 8, 90]
(2, 5, 8, 90)
⁢class 'tuple'>

使用append()方法

使用append()方法將新元素新增到列表的末尾。

示例

以下是如何使用append()方法追加元素的示例:

# converting tuple to list t=(45,67,36,85,32) l = list(t) print(l) print(type(l)) # appending the element in a list l.append(787) print(l) # Converting the list to tuple using tuple() t=tuple(l) print(t)

輸出

以下是上述程式碼的輸出

[45, 67, 36, 85, 32]
⁢class 'list'>
[45, 67, 36, 85, 32, 787]
(45, 67, 36, 85, 32, 787)

更新於:2023年8月22日

12.8萬+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.