---
title: "python 系统学习笔记（六）---元组"
author: "lovnet"
date: "2013-03-06T16:41:00Z"
tags: []
slug: "python"
draft: false
lastmod: "2013-03-07T10:11:04Z"
id: 1825260
url: "https://lovnet.iteye.com/blog/1825260"
---

**元组**

元组和列表十分类似，只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号

分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候，即被使用的元组

的值不会改变。

使用元组

1. #元组由不同的元素组成，每个元素可以存储不同类型的数据，例如字符串、数字和元组
2. #元组通常代表一行数据，而元组中的元素则代表不同的数据项
3. 创建元组，不定长，但一旦创建后则不能修改长度
4. 空元组tuple\_name=()
5. #如果创建的元组只有一个元素，那么该元素后面的逗号是不可忽略的（１，）
6. #不可修改元素

> &gt;&gt;&gt;user=(1,2,3)
> 
> &gt;&gt;&gt;user\[0]=2
> 
> Traceback(mostrecentcalllast):
> 
> File"&lt;pyshell#5&gt;",line1,in&lt;module&gt;
> 
> user\[0]=2
> 
> TypeError:'tuple'objectdoesnotsupportitemassignment
> 
> ```
> test=(1,2,3,4)
print test
test=(test,5)
print test
#元组支持＋和切片操作 
test= test[:1][0] 
print test
#print type(test)
print dir(tuple)

add=(5,)
test=test+add
print test

#去重
print set((2,2,3,4,4))

#解包   
test = (1,2,3)  
a,b,c = test
print a,b,c

#遍历
for elem in test:
    print elem

for item in range(len(test)):
    print test[item]

#二元遍历
test=((1,2),(3,4),(5,6))
for elem in test:
    for item in elem:
        print item
> ```
> 
> **习题**
> 
> **#求序列类型的最大元素和最小元素**
> 
> **#入口:序列类型List**
> 
> **#返回: (最大元素,最小元素) 应用元组**
> 
> **sample**
> 
> ```
> def hello():
    return 'hello','world'
print hello()
> ```