Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a different way to automatically adjust the length of a jupyter list?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading