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 from dan04 on Stack Overflowbuckets = [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
Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:
buckets = [[0 for col in range(5)] for row in range(10)]
to avoid reference sharing between the rows.
This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQ for more details.
Videos
How should I initialize a numpy array of NaN values?
Below is what I tried in the terminal:
>>> import numpy as np >>> x = np.array([0,0,0]) >>> x array([0, 0, 0]) >>> x.fill(np.nan) >>> x array([-9223372036854775808, -9223372036854775808, -9223372036854775808]) >>>