Python - Create a list with initial capacity

Posted by Claudiu on Stack Overflow See other posts from Stack Overflow or by Claudiu
Published on 2008-11-22T20:56:41Z Indexed on 2010/06/11 6:12 UTC
Read the original article Hit count: 181

Filed under:
|
|
|
|

Code like this often happens:

l = []
while foo:
    #baz
    l.append(bar)
    #qux

This is really slow if you're about to append thousands of elements to your list, as the list will have to constantly be re-initialized to grow. (I understand that lists aren't just wrappers around some array-type-thing, but something more complicated. I think this still applies, though; let me know if not).

In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.

I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us python programmers?

© Stack Overflow or respective owner

Related posts about java

Related posts about python