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

python

Solution

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)))

Problem

I am teaching the A level syllabus by the Cambridge exam board. One typical question on the practical paper is this: In a programming language of your choice, declare an array of ten integers and then initializes it. I have this: ``` myArray = [] #create the array for i in range(10): # initializes to 0 myArray.append(0) ``` I believe this is what most people would do in Python? However, unlike Pascal etc it does not strictly answer the question as the 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 size array and type like in Pascal, instead of an empty dynamic list, without any type of loop and restricts the type of the array? Something like (pseudo code): ``` myArray[10] : integer ``` This is a none commercial question but an educational one.

Original source

Related problems