[python] Initialising an array of fixed size in python

I would like to know how i can initialise an array(or list), yet to be populated with values, to have a defined size.

for example in C:

int x[5]; /* declared without adding elements*/

How do i do that in python?

Thanks.

This question is related to python arrays list

The answer is


One thing I find easy to do is i set an array of empty strings for the size I prefer, for example

Code:

import numpy as np

x= np.zeros(5,str)
print x

Output:

['' '' '' '' '']

Hope this is helpful :)


The best bet is to use the numpy library.

from numpy import ndarray

a = ndarray((5,),int)

>>> n = 5                     #length of list
>>> list = [None] * n         #populate list, length n with n entries "None"
>>> print(list)
[None, None, None, None, None]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, None, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, 1, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, 1, 1, 1]

or with really nothing in the list to begin with:

>>> n = 5                     #length of list
>>> list = []                 # create list
>>> print(list)
[]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1]

on the 4th iteration of append:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1]

5 and all subsequent:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1,1]

Do this:

>>> d = [ [ None for y in range( 2 ) ] for x in range( 2 ) ]
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [None, None]]

The other solutions will lead to this kind of problem:

>>> d = [ [ None ] * 2 ] * 2
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [1, None]]

>>> import numpy
>>> x = numpy.zeros((3,4))
>>> x
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> y = numpy.zeros(5)   
>>> y
array([ 0.,  0.,  0.,  0.,  0.])

x is a 2-d array, and y is a 1-d array. They are both initialized with zeros.


Why don't these questions get answered with the obvious answer?

a = numpy.empty(n, dtype=object)

This creates an array of length n that can store objects. It can't be resized or appended to. In particular, it doesn't waste space by padding its length. This is the Python equivalent of Java's

Object[] a = new Object[n];

If you're really interested in performance and space and know that your array will only store certain numeric types then you can change the dtype argument to some other value like int. Then numpy will pack these elements directly into the array rather than making the array reference int objects.


If you are working with bytes you could use the builtin bytearray. If you are working with other integral types look at the builtin array.

Specifically understand that a list is not an array.

If, for example, you are trying to create a buffer for reading file contents into you could use bytearray as follows (there are better ways to do this but the example is valid):

with open(FILENAME, 'rb') as f:
    data = bytearray(os.path.getsize(FILENAME))
    f.readinto(data)

In this snippet the bytearray memory is preallocated with the fixed length of FILENAMEs size in bytes. This preallocation allows the use of the buffer protocol to more efficiently read the file into a mutable buffer without an array copy. There are yet better ways to do this but I believe this provides one answer to your question.


You can try using Descriptor, to limit the size

class fixedSizeArray(object):
    def __init__(self, arraySize=5):
        self.arraySize = arraySize
        self.array = [None] * self.arraySize

    def __repr__(self):
        return str(self.array)

    def __get__(self, instance, owner):
        return self.array

    def append(self, index=None, value=None):
        print "Append Operation cannot be performed on fixed size array"
        return

    def insert(self, index=None, value=None):
        if not index and index - 1 not in xrange(self.arraySize):
            print 'invalid Index or Array Size Exceeded'
            return
        try:
            self.array[index] = value
        except:
            print 'This is Fixed Size Array: Please Use the available Indices'


arr = fixedSizeArray(5)
print arr
arr.append(100)
print arr
arr.insert(1, 200)
print arr
arr.insert(5, 300)
print arr

OUTPUT:

[None, None, None, None, None]
Append Operation cannot be performed on fixed size array
[None, None, None, None, None]
[None, 200, None, None, None]
This is Fixed Size Array: Please Use the available Indices
[None, 200, None, None, None]

Well I would like to help you by posting a sample program and its output

Program:

t = input("")
x = [None]*t
y = [[None]*t]*t

for i in range(1, t+1):
    x[i-1] = i;

    for j in range(1, t+1):
        y[i-1][j-1] = j;

print x
print y

Output :-

2
[1, 2]
[[1, 2], [1, 2]]

I hope this clears some very basic concept of yours regarding their declaration. To initialize them with some other specific values, like initializing them with 0.. you can declare them as:

x = [0]*10

Hope it helps..!! ;)


An easy solution is x = [None]*length, but note that it initializes all list elements to None. If the size is really fixed, you can do x=[None,None,None,None,None] as well. But strictly speaking, you won't get undefined elements either way because this plague doesn't exist in Python.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>