251

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.

0

3 Answers 3

383

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.

Sign up to request clarification or add additional context in comments.

3 Comments

or [{} for _ in range(10)] to avoid lint warnings
something like [0] * 10 is not the way to create 2d list. If you create a list l = [[0]*10]*10], try change l[0][0] = 100, you will find that l[1][0], l[2][0] ... l[9][0] are all set to 100. It is because * replicates reference for object.
Just hit that one. Wound up with [['' for i in range(5)] for j in range(5)] instead of >>> card_strings = [['']*5]*5 >>> card_strings[0][0] = "Well that was unexpected..."
192

list multiplication works.

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

1 Comment

WARNING: This is very prone to error due to pass by reference: self.seen = [[False] * len(board[0])] * len(board) self.seen[row][column] = True # Sets entire column, not one cell
56

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.