除非列表已经用至少i+1个元素初始化,否则不能向xs[i]=value这样的列表赋值。相反,使用xs.append(value)将元素添加到列表末尾。(虽然如果使用字典而不是列表,则可以使用赋值符号。)
创建空列表:
>>> xs = [None] * 10
>>> xs
[None, None, None, None, None, None, None, None, None, None]
为上述列表的现有元素赋值:
>>> xs[1] = 5
>>> xs
[None, 5, None, None, None, None, None, None, None, None]
请记住,像xs[15]=5这样的东西仍然会失败,因为我们的列表只有10个元素。
range(x)从[0,1,2,…x-1]创建列表
# 2.X only. Use list(range(10)) in 3.X.
>>> xs = range(10)
>>> xs
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用函数创建列表:
>>> def display():
... xs = []
... for i in range(9): # This is just to tell you how to create a list.
... xs.append(i)
... return xs
...
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]
列表理解(使用正方形,因为对于范围,您不需要执行所有这些操作,只需返回范围(0,9)):
>>> def display():
... return [x**2 for x in range(9)]
...
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]