Can you create traditional fixed length and type arrays in Python?

You could try to use the array module to specify the type of your array:

import array
a = array.array('i') # Define an integer array.

You can then add the elements you want to the array. I'm not sure whether you can predefine the size your array should have, though. If you want an array of ten integer elements, each element being zero, you could do:

a = array.array('i', [0]*10)

As described in the documentation, the 'i' forces the elements of the array to be integers. Python 2.6 will throw a DeprecationWarning if you try to insert a float in an array of integers, but will cast the float as an int:

>>> a[0]=3.14159
>>> a
>>> array('i', [3, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Alternatively, you could use the numpy package, which lets you define both the size and the type of the array.

import numpy as np
a = np.empty(10, dtype=int) # Define a integer array with ten elements

The np.empty just reserves some space in memory for the array, it doesn't initialize it. If you need an array of 0, you could do:

a[:] = 0

or directly use the np.zeros function:

a = np.zeros(10, dtype=int)

Here again, inserting a float in an array of integers will silently convert the float to integer.

Note a difference between numpy and array: once you define an array in numpy, you cannot change its size without having to recreate an array. In that sense, it satisfies your requirement of "10 and only 10 integers". By contrast, a array.array object can be seen as a list with a fixed element type: the array is dynamic, you can increase its size.


You could use the array module

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

Arrays require that all elements be the same type, as specified when it is created. They can still be appended to however

If you were really determined, you could use the ctypes module to build a C array. But, that is probably not very pythonic as it forces you to do more low level stuff.

import ctypes
intArray10 = ctypes.c_int * 10
myArray = intArray10(*(0 for _ in xrange(10)))

This is a more pythonic way to initialize the list:

>>> l = [0] * 10
>>> l
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> l[1] = 1
>>> l
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]

This, of course, does not answer the question how to create such an un-pythonic thing as a list of restricted elements.

Tags:

Python