# Python元組

``````tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
``````

``````tup1 = ();
``````

``````tup1 = (50,)
## 也可以這樣寫
tup2 = (50)
``````

## 1.存取元組中的值

``````#!/usr/bin/python3

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
``````

``````tup1[0]:  physics
tup2[1:5]:  (2, 3, 4, 5)
``````

## 2.更新元組

``````#!/usr/bin/python3

tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2
print (tup3)
``````

``````(12, 34.56, 'abc', 'xyz')
``````

## 3.刪除元組元素

``````#!/usr/bin/python3

tup = ('physics', 'chemistry', 1997, 2000);

print (tup)
del tup;
print "After deleting tup : "
print (tup)
``````

``````('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
``````

## 4.基本元組操作

Python表示式 結果 描述
`len((1, 2, 3))` `3` 長度
`(1, 2, 3) + (4, 5, 6)` `(1, 2, 3, 4, 5, 6)` 連線操作
`('Hi!',) * 4` `('Hi!', 'Hi!', 'Hi!', 'Hi!')` 重複
`3 in (1, 2, 3)` `True` 成員關係
`for x in (1,2,3) : print (x, end = ' ')` `1 2 3` 疊代

## 5.索引，切片和矩陣

``````T=('C++', 'Java', 'Python')
``````

Python表示式 結果
`T[2]` `'Python'` 偏移量，從零開始
`T[-2]` `'Java'` 負數：從右到左
`T[1:]` `('Java', 'Python')` 切片提取部分

## 6.內建元組函式功能

Python包括以下元組函式 -

1 cmp(tuple1, tuple2) 比較兩個元組的元素。
2 len(tuple) 給出元組的總長度。
3 max(tuple) 從元組返回最大值項。
4 min(tuple) 從元組返回最大值項
5 tuple(seq) 將列表轉換為元組。