Home > Mobile >  Optimise initialisation of several np.zeros() arrays of fixed size in Python
Optimise initialisation of several np.zeros() arrays of fixed size in Python

Time:09-28

I would like to optimise the process of initialising python np.zeros() arrays. Right now I just have a list of them like

import numpy as np

n_elements = 10

a = np.zeros(n_elements)
b = np.zeros(n_elements)
c = np.zeros(n_elements)
d = np.zeros(n_elements)

Do you know how I could make this bulk of code shorter?

I know that

a = b = c = d = np.zeros(n_elements)

Is not an option, since it will be all assigned to one memory slot.

Thanks

CodePudding user response:

You can use numpy directly to generate a 2D array:

a,b,c,d = np.zeros((4, n_elements))

CodePudding user response:

Use a for loop

a, b, c, d = [np.zeros(n_elements) for _ in range(4)]
  • Related