元组:python内置函数的数据结构之一,是一个不可变序列。
不可变序列和可变序列:
不可变序列:字符串、元组
不可变序列:没有增、删、改的操作
可变序列:列表、字典
可变序列:可以对序列执行增、删、改操作,对象地址不发生更改。
列表是使用[ ]
元组是使用()
代码如下:
#打工人:朱乔栋
#革命尚未成功,同志仍需努力
'''不可变序列,可变序列'''
'''可变序列:字典、列表'''
lst=[10,20,25]
print(id(lst))
lst.append(300)
print(id(lst))
'''不可变序列:字符串、元组'''
s='hello'
print(id(s))
s=s+'world'
print(s)
print(id(s)) #可以看到两个字符串连接在一起的时候,内存地址已发生更改了,也就是不可更改序列
yuanzu=('python','wo','ni')
print(yuanzu)
运行结果:
26232272
26232272
26537760
helloworld
31678496
('python', 'wo', 'ni')
Process finished with exit code 0
元组的创建方式:
①直接使用小括号:t=(‘python’,‘50’,‘20’)
②使用内置函数:t=tuple((‘python’,‘50’,‘20’))
③只包含一个元组的元素需要使用逗号和小括号:t=(10,)
代码如下:
#打工人:朱乔栋
#革命尚未成功,同志仍需努力
'''元组的创建方式'''
#第一种方式,使用()
t=('python','98','world')
print(t)
print(type(t))
t1='python','98','world' #省略了小括号
print(t1)
print(type(t1))
t2=('python',) #只有一个元素的时候,逗号必须加上,要不然会以为是另一种数据类型
print(t2)
#第二种创建方式:使用内置函数tuple()
s=tuple(('python','98','world'))
print(s)
print(type(s))
'''空列表'''
lst=[]
lst1=list()
'''空字典'''
d={}
d1=dict()
#空元组
s=()
s1=tuple()
print('空列表:',lst,lst1)
print('空字典:',d,d1)
print('空元组:',s,s1)
运行结果:
('python', '98', 'world')
<class 'tuple'>
('python', '98', 'world')
<class 'tuple'>
('python',)
('python', '98', 'world')
<class 'tuple'>
空列表: [] []
空字典: {} {}
空元组: () ()