Home > Blockchain >  adding numpy arrays to specific indices of a list
adding numpy arrays to specific indices of a list

Time:12-18

I have a list of numpy arrays and want to add two more arrays as the first (0) and last (-1) indices of the list. These are my list and arrays:

import numpy as np
first_arr = np.array([1,1,1])
last_arr = np.array([9,9,9])
middle_arr = [np.array ([4,4,4]), np.array ([6,6,6])]

Then, I want to have a complete_arr which is:

complete_arr = [np.array ([1,1,1]), np.array ([4,4,4]), np.array ([6,6,6]), np.array ([9,9,9])]

I tried the following method but it did not give me what I want:

insert_at = 0
middle_arr[insert_at:insert_at] = first_arr

I very much appreciate if anyone help me to do it in python.

CodePudding user response:

You can use * (unpacking) operator:

first_arr = np.array([1,1,1])
last_arr = np.array([9,9,9])
middle_arr = [np.array ([4,4,4]), np.array ([6,6,6])]

complete_arr = [first_arr, *middle_arr, last_arr]
  • Related