Python基础–09
什么是元组
元组的创建
如果元组中只有一个元素,逗号不能省
t1=('python','world',23)
print(t1)
print(id(t1))
print(type(t1))
# ('python', 'world', 23)
# 1882095097664
# <class 'tuple'>
t2=tuple(('python','world',25))
print(t2)
print(id(t2))
print(type(t2))
# ('python', 'world', 25)
# 1882095097856
# <class 'tuple'>
t3='python','world',23
print(t3)
print(id(t3))
print(type(t3))
# ('python', 'world', 23)
# 1882095097664
# <class 'tuple'>
t=('python',)
print(t)
print(type(t))
# ('python',)
# <class 'tuple'>
t=('python')
print(t)
print(type(t))
# python
# <class 'str'>
#空元组创建方式
t=()
t1=tuple()
为什么元组是不可变序列
t=(10,[20,30],9)
print(t)
# t[1]=100 TypeError: 'tuple' object does not support item assignment
t[1].append(100)
print(t)
# (10, [20, 30], 9)
# (10, [20, 30, 100], 9)
元组的遍历
t=tuple(('python','world',25))
#使用索引获取元组,容易越界
print(t[0])
print(t[1])
print(t[2])
#遍历元组获取元组,不需要知道元祖个数
for item in t:
print(item)