Python 元組(Tuple)詳解:新手指南

更新日期: 2025 年 1 月 22 日

在 Python 編程中,元組(Tuple) 是一種重要的數據結構,與串列(List)類似,但具有不可變(immutable)的特性。

元組在需要存儲不可改變的數據時非常有用,並且可以用作字典(Dictionary)的鍵等。

在本篇文章中,我們將詳細介紹 Python 中的元組,包括其定義、使用方法、特性和實際應用,幫助新手快速掌握元組的概念和用法。


什麼是元組?

元組(Tuple) 是 Python 中的一種序列數據類型,用於存儲多個值的有序集合。

與串列類似,但元組是 不可變的(immutable),也就是說,一旦創建,就不能修改其內容。

特點:

  • 有序性:元組中的元素有固定的位置和順序。
  • 不可變性:元組一旦創建,元素不能被添加、修改或刪除。
  • 允許重複:元組中可以包含重複的元素。
  • 可存儲多種數據類型:元組可以包含不同類型的數據。

如何創建元組

空元組

創建一個空的元組,可以使用一對小括號 ()

empty_tuple = ()
print(empty_tuple)  # 輸出:()
print(type(empty_tuple))  # 輸出:<class 'tuple'>

單元素元組

創建只有一個元素的元組時,需要在元素後面加上一個逗號 ,,否則會被視為普通的數據類型。

single_element_tuple = (5,)
print(single_element_tuple)  # 輸出:(5,)
print(type(single_element_tuple))  # 輸出:<class 'tuple'>

# 錯誤示例
not_a_tuple = (5)
print(type(not_a_tuple))  # 輸出:<class 'int'>

多元素元組

可以在括號內使用逗號分隔元素,創建包含多個元素的元組。

my_tuple = (1, 2, 3, 'a', 'b', 'c')
print(my_tuple)  # 輸出:(1, 2, 3, 'a', 'b', 'c')

省略括號的寫法:

在 Python 中,元組可以在創建時省略括號,直接用逗號分隔元素。

my_tuple = 1, 2, 3
print(my_tuple)  # 輸出:(1, 2, 3)

訪問元組元素

索引訪問

可以使用索引來訪問元組中的元素,索引從 0 開始。

my_tuple = ('a', 'b', 'c', 'd', 'e')
print(my_tuple[0])  # 輸出:'a'
print(my_tuple[2])  # 輸出:'c'

負索引:

從後面開始訪問元素,索引從 -1 開始。

print(my_tuple[-1])  # 輸出:'e'
print(my_tuple[-3])  # 輸出:'c'

切片操作

可以使用切片語法訪問元組中的一段元素。

my_tuple = (0, 1, 2, 3, 4, 5)

# 獲取從索引 1 到 3 的元素(不包含索引 4)
print(my_tuple[1:4])  # 輸出:(1, 2, 3)

# 從頭開始到索引 2(不包含索引 3)
print(my_tuple[:3])  # 輸出:(0, 1, 2)

# 從索引 3 到結尾
print(my_tuple[3:])  # 輸出:(3, 4, 5)

# 步長為 2
print(my_tuple[::2])  # 輸出:(0, 2, 4)

元組的操作

連接元組

可以使用加號 + 將兩個元組連接起來,生成一個新的元組。

tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')

combined_tuple = tuple1 + tuple2
print(combined_tuple)  # 輸出:(1, 2, 3, 'a', 'b', 'c')

重複元組

可以使用乘號 * 將元組重複多次。

my_tuple = ('Hello',) * 3
print(my_tuple)  # 輸出:('Hello', 'Hello', 'Hello')

元組的方法

元組支持的內建方法較少,因為它是不可變的。

count() 方法

返回指定元素在元組中出現的次數。

my_tuple = (1, 2, 3, 2, 2, 4)
print(my_tuple.count(2))  # 輸出:3

index() 方法

返回指定元素在元組中首次出現的索引位置。

print(my_tuple.index(2))  # 輸出:1

元組的不可變性

元組是不可變的,這意味著創建後不能修改其內容。

my_tuple = (1, 2, 3)
# 嘗試修改元素
my_tuple[0] = 10  # TypeError: 'tuple' object does not support item assignment

注意: 雖然元組本身不可變,但如果元組中包含可變物件(如串列),則這些可變物件的內容是可以修改的。

my_tuple = (1, [2, 3], 4)
my_tuple[1][0] = 99
print(my_tuple)  # 輸出:(1, [99, 3], 4)

為什麼使用元組?

數據安全

  • 防止修改:元組的不可變性可以防止數據被意外修改,保證數據的完整性。
  • 作為常量使用:在需要使用常量序列的情況下,元組是一個很好的選擇。

作為字典的鍵

  • 可雜湊性(Hashable):元組是可雜湊的,可以作為字典的鍵或集合的元素。
  • 示例:
  my_dict = {('x', 'y'): 100}
  print(my_dict[('x', 'y')])  # 輸出:100

元組的打包和開箱

元組打包

將多個值賦給一個元組。

my_tuple = 1, 2, 3
print(my_tuple)  # 輸出:(1, 2, 3)

元組開箱

將元組中的元素賦值給多個變量。

a, b, c = my_tuple
print(a)  # 輸出:1
print(b)  # 輸出:2
print(c)  # 輸出:3

使用 * 接收多個值:

my_tuple = (1, 2, 3, 4, 5)
a, *b, c = my_tuple
print(a)  # 輸出:1
print(b)  # 輸出:[2, 3, 4]
print(c)  # 輸出:5

交換變量值

利用元組開箱,可以方便地交換兩個變量的值。

x = 10
y = 20

x, y = y, x
print(x)  # 輸出:20
print(y)  # 輸出:10

嵌套元組

元組可以包含其他元組或串列,形成嵌套結構。

nested_tuple = (1, (2, 3), [4, 5])
print(nested_tuple[1])  # 輸出:(2, 3)
print(nested_tuple[2][1])  # 輸出:5

在函數中使用元組

返回多個值

函數可以通過返回元組來同時返回多個值。

def get_position():
    x = 10
    y = 20
    return x, y

pos = get_position()
print(pos)  # 輸出:(10, 20)

# 開箱
x_pos, y_pos = get_position()
print(x_pos)  # 輸出:10
print(y_pos)  # 輸出:20

串列與元組的轉換

可以使用 list()tuple() 函數在串列和元組之間進行轉換。

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # 輸出:(1, 2, 3)

# 反向轉換
new_list = list(my_tuple)
print(new_list)  # 輸出:[1, 2, 3]

遍歷元組

可以使用 for 迴圈遍歷元組中的元素。

my_tuple = ('a', 'b', 'c')

for item in my_tuple:
    print(item)

輸出:

a
b
c

總結

  • 元組(Tuple) 是一種不可變的有序數據結構,適用於存儲不可改變的數據。
  • 創建元組:使用小括號 () 或直接用逗號分隔元素。
  • 訪問元素:可以使用索引和切片操作。
  • 不可變性:元組一旦創建,無法修改其內容。
  • 應用場景
    • 防止數據被修改。
    • 作為字典的鍵或集合的元素。
    • 在函數中返回多個值。
  • 打包和開箱:可以將多個值打包成元組,或從元組中開箱出多個值。

透過理解和運用元組,您可以編寫出更加安全、高效和可讀性強的 Python 代碼。


延伸閱讀

Similar Posts