Home > Blockchain >  append vectors to empty list
append vectors to empty list

Time:02-05

In a for loop, I read iteratively one vector from file that then I want to put in a list or numpy array. I don't really understand how this process works for numpy arrays or lists. Since I know numpy arrays are not done to change size, I wanted to use an empty list and iteratively append the vector I'm reading

import numpy as np

a = np.array([[1],[2],[3]])
b = np.array([[2],[3],[4]])

c = timeStep = list()

c = c.append(a)
c = c.append(b)

The example above describes what I would like to do but, when I print the c list after appending a, the terminal shows there is nothing inside.

CodePudding user response:

If You want to create a list I suggest you to use:

c = [] #this is an empty list in Python

Now, if You want to append a numpy array in that list, You should use:

c.append(YourNumpyArray)

Your code should look like this:

a = np.array([[1],[2],[3]])
b = np.array([[2],[3],[4]])

c = []

c.append(a)
c.append(b)

print(c)

Notice that You don't need to do c = c.append()

CodePudding user response:

The output of the python REPL

As you can see in the figure also, the append doesn't return anything. It appends to the original array c. So you are overwriting the appended array with None.

This should be the working code for you.

import numpy as np

a = np.array([[1],[2],[3]])
b = np.array([[2],[3],[4]])

c = timeStep = list()

c.append(a)
c.append(b)

On a side note, yes you can use python lists with numpy arrays. If the number of elements in the list c is fixed or pre-known, you can make it a numpy array too.

  •  Tags:  
  • Related