Coder Perfect

[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]

Asked by user1040563

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.

This is what it would look like:

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]
>>> 

Answered by Tiffany

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 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 = [[]] * 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.

Answered by Seppo Erviälä

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

Answered by Andrew Clark

Solution #4

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

Answered by kev

Solution #5

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

zlists[0] contains 0 zeroes, zlists[1] contains 1 zero, zlists[2] contains 2 zeroes, and so on.

Answered by kindall

Post is based on https://stackoverflow.com/questions/8528178/list-of-zeros-in-python