# 在Python中将列表初始化为已知数量的元素

``verts = list (1000)` `

` `verts = [None]*1000` `

` `import array verts=array.array('i',(0,)*1000)` `

` `verts = [0 for x in range(1000)]` `

` `verts = [[0 for x in range(100)] for y in range(10)]` `

`object = [0 for x in range(1000)]`

@Steve已经给你的问题提供了一个很好的答案：

` `verts = [None] * 1000` `

## 备择scheme

` `>>> N = 10**6 >>> %timeit a = [None] * N 100 loops, best of 3: 7.41 ms per loop >>> %timeit a = [None for x in xrange(N)] 10 loops, best of 3: 30 ms per loop >>> %timeit a = [None for x in range(N)] 10 loops, best of 3: 67.7 ms per loop >>> a = [] >>> %timeit for x in xrange(N): a.append(None) 10 loops, best of 3: 85.6 ms per loop` `

` `>>> %timeit a = [x**2 for x in xrange(N)] 10 loops, best of 3: 109 ms per loop >>> def fill_list1(): """Not too bad, but complicated code""" a = [None] * N for x in xrange(N): a[x] = x**2 >>> %timeit fill_list1() 10 loops, best of 3: 126 ms per loop >>> def fill_list2(): """This is slow, use only for small lists""" a = [] for x in xrange(N): a.append(x**2) >>> %timeit fill_list2() 10 loops, best of 3: 177 ms per loop` `

## 与numpy比较

` `from numpy import ndarray, zeros %timeit empty((N,)) 1000000 loops, best of 3: 788 ns per loop %timeit zeros((N,)) 100 loops, best of 3: 3.56 ms per loop` `

` `verts = list(xrange(1000))` `

` ` list = [8 for i in range(9)]` `

` `list = [0] * 7` `

` `aDict = {} aDict[100] = fetchElement() putElement(fetchElement(), fetchPosition(), aDict)` `

`putElement`函数可以将项目存储在任何给定的位置。 如果你需要检查你的集合是否包含给定索引的元素，那么写出更多Pythonic：

` `if anIndex in aDict: print "cool!"` `

` `if not myList[anIndex] is None: print "cool!"` `

``` verts = []
```