0

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]])]
user19862793
  • 169
  • 6
  • Why not directly use `A = [array([[0.4]]), array([[0.15]])]` as you type the arrays anyways? Or maybe you're not faithfully illustrating your real goal? – mozway Sep 03 '22 at 08:02

1 Answers1

2

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)
Schnitte
  • 1,193
  • 4
  • 16