# Python 元組
> 原文: [https://thepythonguru.com/python-tuples/](https://thepythonguru.com/python-tuples/)
* * *
于 2020 年 1 月 7 日更新
* * *
在 Python 中,元組與列表非常相似,但是一旦創建了元組,就無法添加,刪除,替換和重新排序元素。
**注意**:
元組是不可變的。
## 創建一個元組
* * *
```py
>>> t1 = () # creates an empty tuple with no data
>>>
>>> t2 = (11,22,33)
>>>
>>> t3 = tuple([1,2,3,4,4]) # tuple from array
>>>
>>> t4 = tuple("abc") # tuple from string
```
## 元組函數
* * *
元組也可以使用`max()`,`min()`,`len()`和`sum()`之類的函數。
```py
>>> t1 = (1, 12, 55, 12, 81)
>>> min(t1)
1
>>> max(t1)
81
>>> sum(t1)
161
>>> len(t1)
5
```
## 元組迭代
* * *
元組可使用`for`循環進行迭代,[在此處了解有關 for 循環的更多信息](/python-loops/)。
```py
>>> t = (11,22,33,44,55)
>>> for i in t:
... print(i, end=" ")
>>> 11 22 33 44 55
```
## 元組切片
* * *
切片運算符在元組中的作用與在列表和字符串中的作用相同。
```py
>>> t = (11,22,33,44,55)
>>> t[0:2]
(11,22)
```
## `in`和`not in`運算符
* * *
您可以使用`in`和`not in`運算符檢查元組中項的存在,如下所示。
```py
>>> t = (11,22,33,44,55)
>>> 22 in t
True
>>> 22 not in t
False
```
在下一章中,我們將學習 [python 數據類型轉換](/datatype-conversion/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象