How to append multiple lists in Python
Question:
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
[array([[0.4]]),
array([[0.15]])]
Answers:
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)
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
[array([[0.4]]),
array([[0.15]])]
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)