元组:和列表十分相似,可以说是一个受限的列表。最大的限制是,元组不能更改。
创建元组
1 >>> tuple1 = (123,'asd',(1,2,3)) 2 >>> tuple1 3 (123, 'asd', (1, 2, 3))
访问元组
通过索引或元组切片访问元组
1 >>> for i in range(len(tuple1)): 2 ... print(tuple1[i]) 3 ... 4 123 5 asd 6 (1, 2, 3) 7 >>> tuple1[1] 8 'asd' 9 >>> tuple1[1:] 10 ('asd', (1, 2, 3)) 11 >>> tuple1[:1] 12 (123,) 13 >>> tuple1[1:3] 14 ('asd', (1, 2, 3))
更新和删除一个元组
元组对象本身不可变,但是可以通过元组切片创建一个新元组,覆盖原来的元组。
1 >>> tuple1 2 (123, 'asd', (1, 2, 3)) 3 >>> tuple1[0] = 234 4 Traceback (most recent call last): 5 File "<stdin>", line 1, in <module> 6 TypeError: 'tuple' object does not support item assignment 7 >>> tuple1 = tuple1[:1] + (234,) + tuple1[1:] 8 >>> tuple1 9 (123, 234, 'asd', (1, 2, 3))
通过del可以删除一个元组
1 >>> del tuple1[2] 2 Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4 TypeError: 'tuple' object doesn't support item deletion 5 >>> del tuple1 6 >>> tuple1 7 Traceback (most recent call last): 8 File "<stdin>", line 1, in <module> 9 NameError: name 'tuple1' is not defined
元组相关的操作符
- 拼接操作符:+
- 重复操作符:*
- 关系操作符:> >= < <= == !=
- 成员操作符:in not in
- 逻辑操作符:and or not