Python列表和元组

列表

可以将列表当成普通的数组,它能保存任意数量任意类型的python对象
像字符串一样,列表也支持下标和切片操作
列表中的项目可以改变
>>> alist = [1,'tom',2,'alice']
>>> alist[1] = 'bob'
>>> alist
[1, 'bob', 2, 'alice']
>>> alist[2:]
[2, 'alice']
>>> alist = [1,'bob',[10,20]]
>>> alist[2][0]
10
>>> alist[2][1]
20
列表操作
使用in或not in判断成员关系
使用append方法向列表中追加元素
>>> alist[1] = 'bob'
>>> alist = [1,'tom',2,'alice']
>>> 'tom' is alist
False
>>> 'tom' in alist
True
>>> 'tom' not in alist
False
>>> alist.append(3)
>>> alist
[1, 'tom', 2, 'alice', 3]
>>> alist[5] = 'bob'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

>>> alist.append([20,30])
>>> alist
[1, 'tom', 2, 'alice', 3, [20, 30]]
>>> 1 in alist
True
>>> 20 in alist
False

元组

元组的定义及操作
可以认为元组是静态的列表
元组一旦定义,不能改变
>>> atuple = (1,'bob',[10,20])
>>> atuple[0] = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> 
原文地址:https://www.cnblogs.com/weiwenbo/p/6552419.html