Initialise a list to a specific length in Python


How do I initialise a list with 10 times a default value in Python?

I'm searching for a good-looking way to initialize a empty list with a specific range. So make a list that contains 10 zeros or something to be sure that my list has a specific length.

11/4/2010 1:28:34 PM

Accepted Answer

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

6/11/2009 9:14:02 PM

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow