Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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

like image 727
lord12 Avatar asked Mar 30 '13 23:03

lord12


1 Answers

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.

like image 77
Pavel Anossov Avatar answered Sep 24 '22 21:09

Pavel Anossov