Appending multiple lists containing numpy array in Python

Question:

I want to append multiple lists containing a numpy array. I try with append but it doesn’t append the two lists for different t. I present the current and expected outputs.

import numpy as np
N=2
arsigma=[]
for t in range(0,2):
    sigma=0.02109*t*np.ones((2*N*(N+1), 1))
    arsigma.append(sigma)
    arsigma=list(sigma)
    print("sigma =",[sigma])

The current output is

sigma = [array([[0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.],
       [0.]])]
sigma = [array([[0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109],
       [0.02109]])]

The expected output is

sigma=[array([[0.],
           [0.],
           [0.],
           [0.],
           [0.],
           [0.],
           [0.],
           [0.],
           [0.],
           [0.],
           [0.],
           [0.]]), array([[0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109],
           [0.02109]])]
Asked By: user19862793

||

Answers:

Use list comprehension instead:

N = 2
arsigma = [0.02109*t*np.ones((2*N*(N+1), 1)) for t in range(2)]
Answered By: Nuri Taş
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.