How do I get an empty array of any size in Python?

I basically want the Python equivalent of this in C:

int a[x]; 

but in Python I declare an array as:

 a = [] 

and the problem is that I want to assign random slots with values ​​such as:

 a[4] = 1 

but I cannot do this with Python, since the array is empty.

+88
python arrays dynamic-arrays
Mar 05 '11 at 17:43
source share
7 answers

If by "array" you really mean a Python list, you can use

 a = [0] * 10 

or

 a = [None] * 10 
+182
Mar 05 '11 at 17:44
source share

You cannot do exactly what you want in Python (if I read it correctly). You need to put values ​​for each element of the list (or, as you called it, an array).

But try the following:

 a = [0 for x in range(N)] # N = size of list you want a[i] = 5 # as long as i < N, you're okay 

For lists of other types, use something other than 0. None also a good choice.

+16
Mar 05 2018-11-11T00:
source share

You can use numpy:

import numpy as np

Example from an empty array :

 np.empty([2, 2]) array([[ -9.74499359e+001, 6.69583040e-309], [ 2.13182611e-314, 3.06959433e-309]]) 
+11
Sep 13 '14 at 20:23
source share

You can also expand this using the list expansion method.

 a= [] a.extend([None]*10) a.extend([None]*20) 
+5
Mar 05 '11 at 19:36
source share

Just declare a list and add each item. For example:

 a = [] a.append('first item') a.append('second item') 
+2
Oct 25 '16 at 13:07 on
source share

If you (or other searchers for this question) were actually interested in creating a continuous array to fill with integers, consider ByteArray and memoryivew :

 # cast() is available starting Python 3.3 size = 10**6 ints = memoryview(bytearray(size)).cast('i') ints.contiguous, ints.itemsize, ints.shape # (True, 4, (250000,)) ints[0] # 0 ints[0] = 16 ints[0] # 16 
+1
Apr 27 '19 at 17:13
source share

If you really want a C style array

 import array a = array.array('i', x * [0]) a[3] = 5 try: [5] = 'a' except TypeError: print('integers only allowed') 

Note that in python there is no concept of an uninitialized variable. A variable is a name that is associated with a value, so this value must have something. In the above example, the array is initialized to zeros.

However, this is rare in python, unless you need it for low level things. In most cases, it is better to use an empty list or an empty numpy array, as other answers suggest.

0
Jun 06 '19 at 2:06
source share



All Articles