0

How to create list by size without init or default init in Python?

I mean, I want the list to be created with garbage information, so that the creation of list would be fast.

Just like when I declare an array in C

int a[50];

Then when I try to access a[3] directly, it will return garbage information because I haven't initialize it.

Even if I do things like

[None] * length

It still takes about same time as

[3] * length

As I have tested it with length = 10^9.

But in C, these two ways are quite different. The latter one is a "memset", whereas the declaration just allocates the memory without initialization.

Euclid Ye
  • 501
  • 5
  • 13
  • You can't. `int a[50]` simply declares a variable, and Python does not have variable declarations. Instead, you create objects and bind them to a name. – chepner Feb 07 '16 at 03:10
  • When you declare an array in *what*? Python isn't the same like other languages. Even a simple integer is an object and has overhead. The closest I can think of to your example is `numpy.empty((50,), dtype=int)`. Also, if your question isn't version specific, consider editing the tags, while adding other relevant ones, like `list` and `arrays`. – Reti43 Feb 07 '16 at 03:24
  • http://stackoverflow.com/questions/983699/initialise-a-list-to-a-specific-length-in-python. Duplicate. use `[None] * length` – Kenan Banks Feb 07 '16 at 03:34
  • So, does this way of initialization takes extra time to set the values of memory blocks? – Euclid Ye Feb 07 '16 at 07:36
  • It is not duplicate. Why do you flag it as duplicate?? That is not the thing I want. Even if with your way, it still takes the same time as to init with [3] * length. – Euclid Ye Feb 07 '16 at 15:38
  • The Python built-in for arrays is [`array.array()`](https://docs.python.org/2/library/array.html), but I don't think you can allocate the length for an empty array. So you have to use numpy. If you *really* want a list, then what Triptych linked is the answer, whether you like how inefficient or different it is to your C example. If you think your edits about it not being a real duplicate hasn't attracted the desired attention and you're still convinced it isn't, you can discuss it on the [meta](https://meta.stackoverflow.com/). – Reti43 Feb 09 '16 at 01:17

0 Answers0