4

Can I set the capacity of a list when I already know the size the list will eventually have? I'm trying to avoid Python reallocating memory when appending items to it.

In the constructor, setting capacity, size, length or len does not work.

def merge_lists(a, b):
    result = list(capacity=len(a) + len(b))
    ...

Edit: ...without having to actually add any elements.

R2-D2
  • 1,554
  • 1
  • 13
  • 25
  • 3
    Related worth reviewing: [Python - Create a list with initial capacity](http://stackoverflow.com/questions/311775/python-create-a-list-with-initial-capacity) – jedwards Mar 29 '15 at 00:37
  • If you're really looking for speed, consider numpy for numerical arrays or for "C-like" numerical arrays: https://docs.python.org/2/library/array.html – Shashank Mar 29 '15 at 01:04
  • Are you sure you want to do this? It feels like premature optimization to me. – Akavall Mar 29 '15 at 01:09
  • Consider a fixed size deque. I can't say for sure it will offer any optimization though. – Paul Rooney Mar 29 '15 at 03:04

2 Answers2

4

Assuming you want 10 elements, you can do:

l = [None] * 10

or

l = range(10)
Alexandru Godri
  • 528
  • 3
  • 7
  • OK, but I need the list to be empty. – R2-D2 Mar 29 '15 at 00:41
  • Using [None] * 10 basically creates an empty list as None provides that. ("Assigning a value of None to a variable is one way to reset it to its original, empty state.") – Alexandru Godri Mar 29 '15 at 00:45
  • 1
    It seems that OP is after something like reserve in c++ for a vector. Where you can reserve memory for e.g. 10 elements, without affecting vector's size. Both our solution indicate that lists have length, as they are de-facto not empty. – Marcin Mar 29 '15 at 00:49
  • Yes, but after `l.append(42)` it will be `l.index(42) == 10` instead of `0`. – R2-D2 Mar 29 '15 at 00:49
  • Indeed, in C++ you can play around with malloc to create dynamic sized objects. In python you do not have the same liberty. I think this is the best you can get. – Alexandru Godri Mar 29 '15 at 00:51
1

I think the closest you can get is this:

In [1]: result = [0]*100

In [2]: len(result)
Out[2]: 100

This will make result hold 100 elements, before you do anything with it.

Marcin
  • 215,873
  • 14
  • 235
  • 294
  • OK, but I need the list to be empty. – R2-D2 Mar 29 '15 at 00:41
  • So, the answer is most likely no. Python is not c++, where you can manage memory allocation by yourself. Maybe there are some non-standard containers, e.g. [blist](https://pypi.python.org/pypi/blist/?), that can do it. – Marcin Mar 29 '15 at 00:44