I am using for loops to shorten my code for grabbing specific sections of a dataframe and finding the mean and standard deviation. I am then saving those values into a list, since there are different data types.
I wanted to simply initializing the list by writing list=[0,0,0]*(len(cities)) to automatically create an x by 3 list, where x is however many cities there are. The problem with this, as shown in the picture, is that setting a single index to a value, such as list[0][1]=1, doesn’t only affect that index, but instead affects every 3rd column in every row.
I was hoping for a more elegant solution than simply manually counting the number of cities and copy/pasting [0,0,0],…. that many times. I realize a solution is not to use for loops as I did and avoid lists altogether, but that’s not the point for this question.
Simple image of the issue described above. Value being applied to all rows of list.
https://i.stack.imgur.com/hruFz.png
>Solution :
zeros = [[0,0,0] for _ in range(50)]
is one way
but probably better to do
zeros = numpy.zeros((50,3))
(if a numpy.array will suffice)
if you have mixed datatypes you will need to use (e.g. strings and numbers)
zeros = numpy.zeros((50,3),object)