How do I get an empty list of any size in Python?
Asked Answered
H

10

153

I basically want a Python equivalent of this Array in C:

int a[x];

but in python I declare an array like:

a = []

and the problem is I want to assign random slots with values like:

a[4] = 1

but I can't do that with Python, since the Python list is empty (of length 0).

Hymeneal answered 5/3, 2011 at 17:43 Comment(0)
R
299

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

a = [0] * 10

or

a = [None] * 10
Repent answered 5/3, 2011 at 17:44 Comment(3)
One thing you have to watch out for with a = [obj] * N is that the same obj appears in each element of the array. If it a mutable obj, and you modify one item, all will be changed. ...But, for this example using integers (or any other immutable type), it makes no difference. Or, if you just assign to elements, it is not a problem either. (I mention it because I've done exactly that far too often :) )Henandchickens
That bit me hard on my very first Python project, @dappawit. Heed this warning.Bussy
it creates same reference for objectsStaceestacey
H
28

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

But, try this:

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 besides 0. None is often a good choice as well.

Henandchickens answered 5/3, 2011 at 17:46 Comment(2)
This answer borders on the incorrect. range(N) will already produce a list if Python < 3.0.Spain
True, it will produce a list. If you're worried about efficiency, you could use xrange(N) in Python 2.x. I'm not sure how it's bordering on the incorrect, however. I prefer it to a = range(N) because every element starts out at a sensible "default". I guess it's a matter of opinion.Henandchickens
B
22

You can use numpy:

import numpy as np

Example from Empty Array:

np.empty([2, 2])
array([[ -9.74499359e+001,   6.69583040e-309],
       [  2.13182611e-314,   3.06959433e-309]])  
Benedicto answered 13/9, 2014 at 20:23 Comment(1)
np.empty doesn’t actually create an “empty” array – all kinds of weird data will be in there, as the example shows. If it’s a numeric array you want use np.zeros.Fondea
L
7

also you can extend that with extend method of list.

a= []
a.extend([None]*10)
a.extend([None]*20)
Lanni answered 5/3, 2011 at 19:36 Comment(0)
S
5

Just declare the list and append each element. For ex:

a = []
a.append('first item')
a.append('second item')
Ss answered 25/10, 2016 at 13:7 Comment(2)
How would you then 'assign random slots'Cirque
This should at least be in a loop to simulate filling the whole list, like this answer does...Flux
W
3

If you (or other searchers of this question) were actually interested in creating a contiguous 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
Withdrawal answered 27/4, 2019 at 17:13 Comment(0)
A
2

It is also possible to create an empty array with a certain size:

array = [[] for _ in range(n)] # n equal to your desired size
array[0].append(5) # it appends 5 to an empty list, then array[0] is [5]

if you define it as array = [] * n then if you modify one item, all are changed the same way, because of its mutability.

Archiearchiepiscopacy answered 10/11, 2021 at 19:36 Comment(2)
While this is true, and with a good explanation, it doesn't seem that a 2D array is asked, which is what your code produces...Flux
@Flux You are right, my misunderstanding.Archiearchiepiscopacy
O
1
x=[]
for i in range(0,5):
    x.append(i)
    print(x[i])
Oram answered 24/6, 2020 at 11:20 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Suwannee
H
0

If you actually 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 there's no concept of un-initialized variable in python. A variable is a name that is bound to a value, so that value must have something. In the example above the array is initialized with zeros.

However, this is uncommon in python, unless you actually need it for low-level stuff. In most cases, you are better-off using an empty list or empty numpy array, as other answers suggest.

Handfast answered 6/6, 2019 at 14:6 Comment(1)
Just to avoid a possible misunderstanding of "un-initialized": the numpy command np.empty(size) does return a non-initialized array of the given size. Here "not initialized" means that the entries (values in the array) are completely random and usually garbage, resulting from what was earlier in the newly allocated memory. So yes, the variable considered as pointer to the memory is initialized, but the values stored "in it", i.e. there, aren't -- some authors do call this situation an "uninitialized variable", especially in C you would, most probably.Cloddish
C
0

The (I think only) way to assign "random slots" is to use a dictionary, e.g.:

 a = {}     # initialize empty dictionary
 a[4] = 1   # define the entry for index 4 to be equal to 1
 a['French','red'] = 'rouge'  # the entry for index (French,red) is "rouge".

This can be handy for "quick hacks", and the lookup overhead is irrelevant if you don't have intensive access to the array's elements. Otherwise, it will be more efficient to work with pre-allocated (e.g., numpy) arrays of fixed size, which you can create with a = np.empty(10) (for an non-initialized vector of length 10) or a = np.zeros([5,5]) for a 5x5 matrix initialized with zeros).

Remark: in your C example, you also have to allocate the array (your int a[x];) before assigning a (not so) "random slot" (namely, integer index between 0 and x-1).

References:

Cloddish answered 7/4, 2021 at 16:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.