Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Efficient way to create list of same numbers? [duplicate]

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

Answer*

Cancel
4
  • 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.) Commented Mar 30, 2013 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. Commented Mar 30, 2013 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. Commented Mar 31, 2013 at 2:46
  • 2
    @Jaime: Also note that empty + fill is faster than repeat Commented Mar 31, 2013 at 2:55