Python 支持多種 復合 數據類型,可將不同值組合在一起。最常用的 列表 ,是用方括號標注,逗號分隔的一組值。列表 可以包含不同類型的元素,但一般情況下,各個元素的類型相同:
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
和字符串(及其他內置 sequence 類型)一樣,列表也支持索引和切片:
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
切片操作返回包含請求元素的新列表。以下切片操作會返回列表的 淺拷貝:
>>> squares[:]
[1, 4, 9, 16, 25]
列表還支持合並操作:
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
與 immutable 字符串不同, 列表是 mutable 類型,其內容可以改變:
>>> 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]
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]
為切片賦值可以改變列表大小,甚至清空整個列表:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
內置函數 len()
也支持列表:
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
還可以嵌套列表(創建包含其他列表的列表),例如:
>>> 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'