# 元組tuple型態

元組型態和串列十分地類似，幾乎唯一的差別只在於元組的內容一旦設定之後就不能修改，除了速度上的考量之外，有些時候也是為了整理或傳遞資料的方便性。宣告元組型態的方法，使用的是小括號，如下所示：

```python
a = (20, 30, 50, 34)
print(type(a))
b = tuple("askidkjxjekek")
print(b)
```

執行結果如下所示：

```
<class 'tuple'>
('a', 's', 'k', 'i', 'd', 'k', 'j', 'x', 'j', 'e', 'k', 'e', 'k')
```

上述的程式碼中，不論是a或是b，在建立了元組變數之後，就不能夠再以任何的方式去修改裡面的內容，不只是沒有像串列型態一樣的append()添加元素的函式，就連指定其中某一項目的值也是不被允許的，如下：

```python
a = (20, 30, 50, 34)
print(a[2])
a[2] = 100
```

上述程式的執行結果如下所示：

```
50
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-aef5d1a8539e> in <module>
      1 a = (20, 30, 50, 34)
      2 print(a[2])
----> 3 a[2] = 100

TypeError: 'tuple' object does not support item assignment
```

元組型態的變數經常被拿來把某一些在邏輯上在一起的數值放在一起，例如想要設定某一個座標，就經常會用元組把x, y座標值綁在一起，如下所示：

```python
def sub(coord, d):
    return coord[0]+d, coord[1]+d

print(sub((100, 200), 10))
```

這個程式的傳回值就會是一個元組的型態，也就是(110, 210)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nkust.gitbook.io/python/yuan-tuple-xing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
