How to create an integer array in Python?

It should not be so hard. I mean in C,

int a[10]; 

is all you need. How to create an array of all zeros for a random size. I know the zeros() function in NumPy but there must be an easy way built-in, not another module.


Solution 1:

If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:

import array
array.array('i')

See here

If you need to initialize it,

a = array.array('i',(0 for i in range(0,10)))

Solution 2:

two ways:

x = [0] * 10
x = [0 for i in xrange(10)]

Edit: replaced range by xrange to avoid creating another list.

Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.

Solution 3:

>>> a = [0] * 10
>>> a
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]