I want to initialize an empty list of given size. I've found the following on SO:lst = [None] * n
What is complexity of this piece of code? Is it constant or linear? If it's linear then what are the constant ways?
2
votes
1 Answers
4
votes
Creating a list of size N will always be O(N) in Python. If you want to create lists in constant time but with variable length, you'll need to write your own data structure which does it in a "virtual" way. For example, imagine a class similar to list but with an extra member "_virtual_len" which is returned by __len__(). Then when iterating, this special list-like class can iterate over the actual values it contains, plus some number of "empty" values to reach _virtual_len. Constructing such a list would be O(1).