列表使用[ ],列表包含的元素可以是多种不同的类型;
In [1]: squares = [1, 4, 9, 16, 25] In [2]: squares Out[2]: [1, 4, 9, 16, 25]
跟字符串一样,列表也可以使用索引和切片:
In [3]: squares[0] Out[3]: 1 In [4]: squares[-1] Out[4]: 25 In [5]: squares[-3:] Out[5]: [9, 16, 25]
所有的切片操作都会返回一个新的包含切片内容的新列表,以下操作表示生成一个原列表的副本:
In [6]: squares[:] Out[6]: [1, 4, 9, 16, 25]
列表也支持连接符:
In [7]: squares + [36, 49, 64, 81, 100] Out[7]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
列表是可变的,与字符串不同:
In [8]: cubes = [1, 8, 27, 65, 125] In [9]: 4 ** 3 Out[9]: 64 In [10]: cubes[3] = 64 In [11]: cubes Out[11]: [1, 8, 27, 64, 125]
使用append函数可以在列表的末尾添加新元素:
In [12]: cubes.append(216) In [13]: cubes.append(7 ** 3) In [14]: cubes Out[14]: [1, 8, 27, 64, 125, 216, 343]
给切片分配新的内容也可以:
In [15]: letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] In [16]: letters Out[16]: ['a', 'b', 'c', 'd', 'e', 'f', 'g'] In [17]: letters[2:5] = ['C', 'D', 'E'] In [18]: letters Out[18]: ['a', 'b', 'C', 'D', 'E', 'f', 'g'] In [19]: letters[2:5] = [] In [20]: letters Out[20]: ['a', 'b', 'f', 'g'] In [21]: letters[:] = [] In [22]: letters Out[22]: []
使用内置函数len也可以计算列表的长度:
In [23]: letters = ['a', 'b', 'c', 'd'] In [24]: len(letters) Out[24]: 4
也可以在列表中放进列表:
In [25]: a = ['a', 'b', 'c'] In [26]: n = [1, 2, 3] In [27]: x = [a, n] In [28]: x Out[28]: [['a', 'b', 'c'], [1, 2, 3]] In [29]: x[0] Out[29]: ['a', 'b', 'c'] In [30]: x[0][1] Out[30]: 'b'