What is the fastest way to make a list-like object containing integers/floats (very simple datatypes) in python?
What do I mean by "list-like"?
This means I want to have an object that supports the two (very) basic operations of a list: getting an object in a certain index (1) and changing its value (2).
What posts did I come across before posting this and why didn't they solve my problem?
I came across these two: [1] [2]
They didn't solve my problem because all the solutions to them were simply too slow: in my PC array.array('i',(0,)*10 ** 8)
resulted in an error (lol); [0 for _ in range(10**8)]
took about 15 seconds (wow!); [0] * 10 ** 8
took 2.3 seconds; [None] * 10 ** 8
took 1.8 seconds; (1.8sec could be faster...)
What did I try to do?
I tried using the ctypes
module
from ctypes import c_int
array = (c_int * 10 ** 8)()
The code above took only 0.7 seconds ... but is there a way to make it faster? Besides being fast it has some disadvantages:
- As it uses the c/c++ variables' skeleton, the integers in it will be in a "not as unlimited as python" integer value range
- You can't have more than one datatype in the list
- You have to import a module to use it
Is it really possible to do what I'm asking? Is there a faster way rather than using the ctypes
module? If so make sure that you are using a 'built-in' / 'pre-installed' module.
Edit:
Why can't I simply install some module, like numpy?
I'm using python for competitive programming and most interpreters/judges just won't allow external libraries.
Can we have custom objects stored with array.array?
I can see many of the answers use the array
function of the array
module. They all use 'i' to specify we want to store integers. Is it possible to make a class and create an `array.array' containing it? For example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# make array.array object with all indexes containing a Point with atributes x and y with value 0
# an example with a list of what I want to do is this:
# l = [Point(0, 0) for _ in range(10**3)]