1、关于元组
元组是不可变序列,没有增删改操作
可变序列有列表、字典
不可变序列有字符串、元组
#对于列表
lst = [10,20,30]
print(id(lst))
lst.append(100)
print(id(lst)) #内存地址不变
输出结果:
1327015940616
1327015940616
内存地址不变
#对于字符串
s = 'hello'
print(id(s))
s = s + 'world'
print(id(lst)) #内存地址改变了
输出结果:
1327016441456
1327015940616
内存地址改变了
元组和列表从外表上看就差在一个()和 [ ]
2、元组的创建方式
2.1 第一种方式:使用()
t = ("hello","world",98)
print(t)
print(type(t))
输出结果:
(‘hello’, ‘world’, 98)
<class ‘tuple’>
也可以不加括号
#可以不用加括号
t = "hello","world",98
print(t)
print(type(t))
输出结果:
(‘hello’, ‘world’, 98)
<class ‘tuple’>
但只有一个元素时,
#但只有一个元素时,
t = "hello"
print(t)
print(type(t))
t = ("hello")
print(t)
print(type(t))
#加不加括号都会输出str类型
输出结果:
hello
<class ‘str’>
hello
<class ‘str’>
加不加括号都会输出str类型
当元组只有一个元素时,要加小括号()和逗号,
#当元组只有一个元素时,要加小括号()和逗号,
t = ("hello",) #如果元组中只有一个元素,逗号不能省
print(t)
print(type(t))
输出结果:
(‘hello’,)
<class ‘tuple’>
2.2 第二种创建方式:用内置函数tuple()
t1 = tuple(("hello","world",98))
print(t1)
print(type(t1))
输出结果:
(‘hello’, ‘world’, 98)
<class ‘tuple’>
3、空元组的创建
复习一下空列表、空字典的创建
#空列表 两种方法
lst = []
lst1 = list()
print('空列表',lst,lst1)
输出结果:
空列表 [] []
#空字典 两种方法
d = {}
d1 = dict()
print('空字典',d,d1)
输出结果:
空字典 {} {}
空元组的创建也有两种方式
#空元组
t4 = ()
t5 = tuple()
print('空元组',t4,t5)
输出结果:
空元组 () ()
4、为什么要将元组设置成不可变序列
…
如果元组中对象本身就是不可变对象,则不能再引用其他对象
如果元组中对象本身是可变对象,则可变对象的引用不可改变,但数据可以改变(添、减内容)
t = (10,[20,30],9)
#尝试将t[1]改为100
#t[1] = 100 #会报错,元素是不允许修改元素的
#由于[20,30]是列表,而列表是可变序列,所以可以向列表中添加元素,而列表的内存地址不变
print(id(t))
print(id(t[1]))
t[1].append(100)
print(t[1])
print(id(t[1]))
print(t)
print(id(t))
输出结果:
2519522472888
2519518761480
[20, 30, 100]
2519518761480
(10, [20, 30, 100], 9)
2519522472888
从结果看来,在元组内的列表对象的数据之后,列表与元组的内存地址都未发生改变;因此增添改不可变对象内的可变对象的数据是被允许的
5、元组元素的遍历
t = ('hello','world',98)
for item in t:
print(item)
输出结果:
hello
world
98