# [duplicate] Python list of zeros

## Problem

How can I make a list that only contains zeros? I’d like to be able to generate a zeros list for each integer in the range (10)

For example, if the range’s int was 4, I’d get:

``````[0,0,0,0]
``````

and for 7:

``````[0,0,0,0,0,0,0]
``````

## Solution #1

``````#add code here to figure out the number of 0's you need, naming the variable n.
listofzeros = [0] * n
``````

If you’d rather put it in a function, simply paste that code in and add return listofzeros.

Which would look like this:

``````def zerolistmaker(n):
listofzeros = [0] * n
return listofzeros
``````

sample output:

``````>>> zerolistmaker(4)
[0, 0, 0, 0]
>>> zerolistmaker(5)
[0, 0, 0, 0, 0]
>>> zerolistmaker(15)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>>
``````

## Solution #2

``````\$python 2.7.8

from timeit import timeit
import numpy

timeit("list(0 for i in xrange(0, 100000))", number=1000)
> 8.173301935195923

timeit("[0 for i in xrange(0, 100000)]", number=1000)
> 4.881675958633423

timeit("[0] * 100000", number=1000)
> 0.6624710559844971

timeit('list(itertools.repeat(0, 100000))', 'import itertools', number=1000)
> 1.0820629596710205
``````

To make a list containing n zeros, you should use [0] * n.

See why [] is more efficient than a list ()

However, both itertools have a catch. repeat and [0] * n will generate lists with the same id as the elements. This is not a problem with immutable objects like integers or strings but if you try to create list of mutable objects like a list of lists ([[]] * n) then all the elements will refer to the same object.

``````a = [[]]&nbsp;* 10
a[0].append(1)
a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
``````

[0] * n creates the list instantaneously, whereas repeat creates the list slowly when it is accessed for the first time.

Numpy arrays are superior if you’re dealing with a lot of data and your problem doesn’t require changeable list lengths or multiple data types within the list.

``````timeit('numpy.zeros(100000, numpy.int)', 'import numpy', number=1000)
> 0.057849884033203125
``````

In addition, numpy arrays will use less RAM.

## Solution #3

Multiplying a one-element list by n is the simplest approach to make a list with all the same values.

``````>>> [0] * 4
[0, 0, 0, 0]
``````

So here’s the deal with your loop:

``````for i in range(10):
print [0] * i
``````

## Solution #4

``````\$ python3
>>> from itertools import repeat
>>> list(repeat(0, 7))
[0, 0, 0, 0, 0, 0, 0]
``````

``````zlists = [[0] * i for i in range(10)]