6

What is the most efficient way to create list of the same number with n elements?

lord12
  • 2,837
  • 9
  • 35
  • 47

1 Answers1

16
number = 1
elements = 1000

thelist = [number] * elements

>>> [1] * 10
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

NB: Don't try to duplicate mutable objects (notably lists of lists) like that, or this will happen:

In [23]: a = [[0]] * 10

In [24]: a
Out[24]: [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]

In [25]: a[0][0] = 1

In [26]: a
Out[26]: [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

If you are using numpy, for multidimensional lists numpy.repeat is your best bet. It can repeat arrays of all shapes over separate axes.

Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • 2
    The question is tagged `numpy` too, so maybe mention `numpy.repeat(1, 10)`? (Although it'll be slower than multiplying a list until `n` is really big.) – DSM Mar 30 '13 at 23:05
  • 2
    Note that this may have unexpected results (depending on how much you know of how Python variables work) with mutable types - it produces a list of references to the same object. – Gareth Latty Mar 30 '13 at 23:08
  • 1
    To honor the numpy tag, `a = np.empty((elements,), dtype=np.int); a.fill(number)` is much faster than `[number] * elements` for higher values of `elements`. But the return is not a real list. – Jaime Mar 31 '13 at 02:46
  • 2
    @Jaime: Also note that `empty` + `fill` is faster than `repeat` – Warren Weckesser Mar 31 '13 at 02:55