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

How to append multiple lists in Python

I want to append two lists A[0] and A but I am getting an error. I present the expected output.

import numpy as np
A=[]
A[0]=[np.array([[0.4]])]
A=[np.array([[0.15]])]
print("A =",A)

The error is

in <module>
    A[0]=[np.array([[0.4]])]

IndexError: list assignment index out of range

The expected output is

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

[array([[0.4]]),
 array([[0.15]])]

>Solution :

In your code, A[0] is not a list; it’s an element (the first one, to be precise) in list A. But A is empty, so there is no element A[0]in it that you can assign a value to, hence the "index out of range" error. Try the following instead:

import numpy as np
A=[]
A.append(np.array([[0.4]]))
A.append(np.array([[0.15]]))
print("A =",A)
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