ChatGPT解决这个技术问题 Extra ChatGPT

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

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


S
Sven Marnach

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

a = [0] * 10

or

a = [None] * 10

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 :) )
That bit me hard on my very first Python project, @dappawit. Heed this warning.
it creates same reference for objects
d
dappawit

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.


This answer borders on the incorrect. range(N) will already produce a list if Python < 3.0.
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.
r
raggot

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

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.
P
Pythoni

also you can extend that with extend method of list.

a= []
a.extend([None]*10)
a.extend([None]*20)

L
Lyle

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

a = []
a.append('first item')
a.append('second item')

How would you then 'assign random slots'
This should at least be in a loop to simulate filling the whole list, like this answer does...
J
Jay

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

E
Ersoy
x=[]
for i in range(0,5):
    x.append(i)
    print(x[i])

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.
a
armiro

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.


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...
@Tomerikoo You are right, my misunderstanding.
b
blue_note

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.


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.
M
Max

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:

The dict datatype: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

Function np.empty(): https://numpy.org/doc/stable/reference/generated/numpy.empty.html