The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Question
00:45 Accepted answer (Score 506)
01:07 Answer 2 (Score 144)
01:40 Answer 3 (Score 28)
01:54 Answer 4 (Score 24)
02:16 Thank you

--

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

Accepted answer links:
[this technique doesn't generalize to multidimensional arrays or lists of lists]: https://docs.python.org/3/faq/programmin...
[List of lists changes reflected across sublists unexpectedly]: https://stackoverflow.com/questions/2401...

Answer 2 links:
[Python FAQ]: http://docs.python.org/faq/programming.h...

--

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