1、列表的表现形式
最常用的列表,是用方括号标注,逗号分隔的一组值。
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
注:
列表可以包含不同类型的元素
2、列表索引
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
3、列表切片
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
4、列表合并
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
5、列表修改
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
6、列表添加元素
append() 方法可以在列表结尾添加新元素
>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
7、列表长度
内置函数 len() 返回列表的长度
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
8、列表嵌套
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'