Binary Lion Studios

I code for fun and for food.

Create a list with same value repeated

A handy way to create a list with the same value repeated.

1
2
3
>>> n = 10
>>> [0] * n
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

This trick is also nifty for plotting data, where you need all points on the y-axis without a value to be a given number (usually 0).

1
2
3
4
5
6
7
8
>>> n = 5
>>> x = range(5)
>>> x
[0, 1, 2, 3, 4]
>>> zip(x, [0] * n)
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]
>>> dict(zip(x, [0] * n))
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0}