# [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 =  * n
``````

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

This is what it would look like:

``````def zerolistmaker(n):
listofzeros =  * 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(" * 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  * n.

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

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

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

 * 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.

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

So here’s the deal with your loop:

``````for i in range(10):
print  * i
``````

## Solution #4

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

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