The Python Oracle

How to declare array of zeros in python (or an array of a certain size)

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 How To Declare Array Of Zeros In Python (Or An Array Of A Certain Size)
00:30 Accepted Answer Score 527
00:45 Answer 2 Score 152
01:12 Answer 3 Score 31
01:23 Answer 4 Score 25
01:37 Answer 5 Score 21
01:47 Thank you

--

Full question
https://stackoverflow.com/questions/4056...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 527


buckets = [0] * 100

Careful - this technique doesn't generalize to multidimensional arrays or lists of lists. Which leads to the List of lists changes reflected across sublists unexpectedly problem




ANSWER 2

Score 31


You can multiply a list by an integer n to repeat the list n times:

buckets = [0] * 100



ANSWER 3

Score 25


Use this:

bucket = [None] * 100
for i in range(100):
    bucket[i] = [None] * 100

OR

w, h = 100, 100
bucket = [[None] * w for i in range(h)]

Both of them will output proper empty multidimensional bucket list 100x100




ANSWER 4

Score 21


use numpy

import numpy
zarray = numpy.zeros(100)

And then use the Histogram library function