Is it possible to create a(n uninialized) Python list of n integers in [0,n) in O(1) time?

Viewed 67

The following Python code creates a(n initialized) list of n nonnegative integers, each of which is at most n-1:

a = [0] * n

I assume that the instruction takes O(n) time due to the initialization. Is there is a way in Python to obtain a list of n integers in O(1) time? I don't care whether the list is initialized or not. I just want the time complexity be O(1). I also want the list mutable and supporting O(1)-time access and update for the i-th entry. This can be easily done in C via malloc. How about Python?

1 Answers

I suggest you, use NumPy to create a list if you want speed. Just create a list using NumPy with different values you can initialize it with zeros or random values also by just calling different function. This is the fastest way I know to get the list.

import numpy as np
my_array = np.zeros(n)
Related