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

I am studying a level A program on the Cambridge exam board. One typical question in practical work:

In a programming language of your choice, declare an array of ten integers and then initialize it.

I have it:

myArray = [] #create the array for i in range(10): # initializes to 0 myArray.append(0) 

I believe that most people will do this in Python? However, unlike Pascal, etc., it does not strictly answer the question, since lists in Python are essentially dynamic arrays with the added problem of not restricting the data type of each element. Can I declare a specific dimensional array and type, as in Pascal, instead of an empty dynamic list without any type of loop and restricts the type of array?

Something like (pseudo-code):

 myArray[10] : integer 

This is not a commercial issue, but an educational one.

+7
source share
6 answers

You can use an array module

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

Arrays require all elements to be of the same type as specified when creating it. They can still be added to

If you were really sure, you can use the ctypes module to create an array of C. But this is probably not very Pythonic, as it forces you to do lower-level things.

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

You can try using array module to indicate the type of your array:

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

Then you can add the elements you want to the array. I'm not sure if you can predetermine the size your array should have. If you need an array of ten integer elements, each element of which is zero, you can do:

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

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

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

Alternatively, you can use the numpy package, which allows you to determine both the size and type of the array.

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

np.empty just reserves some memory space for the array, it does not initialize it. If you need an array of 0, you can do:

 a[:] = 0 

or directly use the np.zeros function:

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

In this case, inserting a float into an array of integers will silently convert the float to integer.

Note the difference between numpy and array : once you define an array in numpy , you cannot resize it without having to create an array. In this sense, it satisfies your requirement "10 and only 10 integers." On the contrary, the object array.array can be considered as a list with a fixed type of element: the array is dynamic, you can increase its size.

+10
source

This is a more Putin way of initializing a 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 of how to create such a non-python thing, such as a list of restricted elements.

+6
source

As already mentioned, l = [0] * 10 initializes a list with 10 zeros.

While you can add a few more elements, you cannot do this by mistake.

 >>> l = [0] * 10 >>> l[10] = 1 Traceback (most recent call last): l[10] = 1 IndexError: list assignment index out of range 

If you want to add to the list, you need to call .append() or some other method that will add new elements. Thus, you cannot add elements randomly, you need to be explicit .

In many other languages, you can simply replace the array with one that has a different size. Point, you can often find a way to overcome such limitations, and I find it good to use the easiest thing that works and is well understood.

For me it will be

 >>> l = [0] * 10 
+2
source
 class myTypedArray: def __init__(self,mytype): self._internalList = [] self._internalType = mytype def add(self,x): if type(x) == self._internalType: self._internalList.append(x) #else raise an Error to warn User of typedArray def __str__(self): s = "" for x in self._internalList: s+=str(x) return s x = myTypedArray(int) x.add(1) x.add("xyz") # will not be added print x # output: 1 

If you want to limit the size, you can track the size and throw an exception. Therefore, type extension in Python is very simple, as you can see. The whole point of static typed languages ​​like C should be closer to the hardware. This myTypedArray example is inefficient, so there is usually no reason to use static types.

0
source

You can do this with an array module. The array module is part of the Python standard library:

 from array import array from itertools import repeat a = array("i", repeat(0, 10)) # or a = array("i", [0]*10) 

repeat function repeats the value 0 by 10 times. It is more memory efficient than [0] * 10 because it does not allocate memory, but repeats, returning the same number x the number of times.

0
source

All Articles