248

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.

Janusz
  • 187,060
  • 113
  • 301
  • 369

3 Answers3

375

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.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 29
    or [{} for _ in range(10)] to avoid lint warnings – Martin Konecny May 03 '13 at 01:22
  • 10
    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. – John Wu Sep 29 '14 at 13:31
  • 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..." – RobotHumans Sep 19 '15 at 09:18
191

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
eduffy
  • 39,140
  • 13
  • 95
  • 92
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.

xoxox
  • 719
  • 1
  • 13
  • 24
Pejvan
  • 772
  • 5
  • 8