# Tuples元組
> [color=#40f1ef][name=LHB阿好伯, 2020/12/02][:earth_africa:](https://www.facebook.com/LHB0222/)
###### tags: `Python_30` `R & python`
[TOC]
Tuple也稱作元組,tuple其實與List很像
元組是有序且不可更改(不可變)的不同資料類型
元組用圓括號()表示
創建元組後,我們將無法更改其值
我們不能在元組中使用添加,插入,刪除函數
因為它不可修改
這點是與清單最大的不同
然而在R語言中似乎不常使用這種資料類型
我這邊就不再介紹了
:::danger
tuple() #創建一個空的元組
:::
# Tuples創建
```python=
# Python code
empty_tuple = ()
type(empty_tuple)
#或使用tuple構造函數
empty_tuple = tuple()
```
:::success
<class 'tuple'>
:::
```python=+
fruits = ('banana', 'orange', 'mango', 'lemon')
print(fruits)
```
:::success
('banana', 'orange', 'mango', 'lemon')
:::
## Tuples資料索引與擷取
Tuples索引與擷取方式與[Lists清單](/vCN7TwuWRKW-QDmoznnbSA)都是使用方括弧 ==[]== 我這邊就不在贅述
## 串接Tuples
方法與list相同都是使用加號 ==+==
```python=
# Python code
tpl1 = ('item1', 'item2', 'item3')
tpl2 = ('item4', 'item5','item6')
tpl3 = tpl1 + tpl2
print(tpl3)
```
:::success
('item1', 'item2', 'item3', 'item4', 'item5', 'item6')
:::
## Tuples轉換為Lists
若是有需要Tuples與Lists之間是可以進行轉換的
```python=
# Python code
tpl = ('item1', 'item2', 'item3','item4')
lst = list(tpl)
type(tpl)
type(lst)
```
:::success
<class 'tuple'>
<class 'list'>
:::
# 搜尋Tuples
我們可以使用 ==in== 來檢查列表中是否存在某項
返回一個布爾值
```python=
# Python code
tpl = ('item1', 'item2', 'item3','item4')
'item2' in tpl
```
:::success
True
:::
# 刪除
無法刪除Tuples中的單個項目
但可以使用 ==del== 刪除Tuples本身
:::danger
tpl1 = ('item1', 'item2', 'item3')
del tpl1
:::
```python=
# Python code
fruits = ('banana', 'orange', 'mango', 'lemon')
del fruits
print(fruits)
```
:::success
NameError: name 'fruits' is not defined
:::
全文分享至
https://www.facebook.com/LHB0222/
有疑問想討論的都歡迎於下方留言
喜歡的幫我分享給所有的朋友 \o/
有所錯誤歡迎指教
# [:page_with_curl: 全部文章列表](https://hackmd.io/@LHB-0222/AllWritings)
