目录
元组
- Python内置的数据结构之一,是一个不可变序列
不可变序列与可变序列
- 不可变序列:字符串、元组
- 没有增、删、改操作
- 可变序列:列表、字典
- 可以对序列进行增、删、改操作,且对象地址不发生改变
一、元组的创建
- 使用小括号 () 注意:只包含一个元素的元组,元素后逗号不能省略
- 使用内置函数 tuple()
'''使用()创建元组'''
t=('小王','c',98)
print(t,type(t),id(t))
#也可以省略小括号
t1='小王','c',98
print(t1,type(t1),id(t1))
'''使用内置函数tuple()创建元组'''
t2=tuple(('小王','c',98))
print(t2,type(t2),id(t2))
'''创建空元组'''
t3=()
t4=tuple()
print(t3,type(t3),id(t3))
print(t4,type(t4),id(t4))
运行结果
二、元组的遍历
2.1 元组元素的获取
- 使用 [ ] 注意:当 [ ] 内索引值超出范围时会抛出 IndexError
t=('小王','c',98)
print(t[0])
print(t[1])
print(t[2])
运行结果
2.2 元组的遍历
for 迭代变量 in 元组名
循环体
t=('小王','c',98)
for i in t:
print(i)
运行结果
Flag:我要成为一个日更选手:)