元组
一、元组
- python内置的数据结构之一,是一个不可变序列
二、不可变序列与可变序列
不可变序列:字符串、元组
- 不可变序列:没有增、删、改的操作
可变序列:列表、字典
- 可变序列:可以对序列进行增、删改操作,对象地址不发生更改
''' 可变序列:列表、字典 ''' lst=[10,20,45] print(id(lst)) lst.append(100) print(id(lst)) ''' 不可变序列:字符串、元组 ''' s='hello' print(id(s)) s=s+'world' print(id(s)) 运行结果: 2232750129536 2232750129536 2232750141168 2232750463280
三、元组的创建方式
1、直接小括号
2、使用内置函数tuple()
3、只包含一个元组的元素需要使用逗号和小括号
'''
第一种创建方式——使用()
'''
demo1=('hello','world',98)
print(demo1)
print(type(demo1))
demo2='hello','world',98
print(demo2)
print(type(demo2))
demo3='hello'
print(demo3)
print(type(demo3)) #<class 'str'>
#在这里,我们发现其是str类型,不再是元组类型,对于只有一个数据的元组,我们需要使用括号或者是逗号
demo4='hello',
print(demo4)
print(type(demo4))#<class 'tuple'>
'''
第二种方法——使用内置函数tuple()
'''
demo5=tuple(('python','world',98))
print(demo5)
print(type(demo5))
#空列表的创建方式
lst=[]
lst1=list()
#空字典的创建方式
d={}
d2=dict()
#空元组的创建方式
t=()
t2=tuple()
print(t)
四、为什么要将元组设计成不可变序列
- 在多任务环境中,同时操作对象时不需要加锁
- 因此,在程序中尽量使用不可变序列
注意事项:
- 元组中存储的是对象的引用
- 如果元组中对象本身为不可变对象,则不能再引用其他对象
- 如果元组中对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
demo=(10,[20,30],9) print(demo) print(demo[0],type(demo[0]),id(demo[0])) #<class 'int'> print(demo[1],type(demo[1]),id(demo[1])) #<class 'list'> print(demo[2],type(demo[2]),id(demo[2])) #<class 'int'> #demo[0]=100 报错:元组是并不允许修改元素的——TypeError: 'tuple' object does not support item assignment ''' 由于列表是可变序列,所以可以改变列表,向列表中添加元素,而列表的内存地址不变 ''' demo[1].append(100) #向列表中添加元素 print(demo[1],id(demo[1])) #可以发现其id号不变 运行结果: (10, [20, 30], 9) 10 <class 'int'> 1731897420368 [20, 30] <class 'list'> 1731902849344 9 <class 'int'> 1731897420336 [20, 30, 100] 1731902849344
五、元组的遍历
demo=('python','world',98)
'''
两种方法遍历元组
1、使用索引
2、使用for循环遍历
'''
for i in demo:
print(i)
运行结果:
python
world
98
浙公网安备 33010602011771号