Reputation: 6651
In initializing my code, I need to create several numpy arrays all of the same shape. It's straightforward to do
>>> nx=10
>>> ny=10
>>> a = np.zeros((ny,nx))
>>> b = np.copy(a)
>>> c = np.copy(a)
>>> d = np.copy(a)
>>> etc.
but it is certainly tedious. I was hoping there might be a one-liner to do this. I tried
>>> (b,c,d,e,f,g) = 6*[np.copy(a)]
but that gives me several references to a
, not independent copies.
Is there something similar that will give independent copies?
Upvotes: 1
Views: 97
Reputation: 7040
We can take advantage of tuple unpacking here. If you're creating a standard Numpy array (zeros, ones, eye, etc.) then you can do it by setting the outermost value of the shape to the number of copies you'd like:
a, b, c, d, e, f, g = np.zeros((7, ny, nx))
Be aware that if you create your "copies" this way, they're actually all slices into the same array.
If you would actually like to make copies of a particular array (and not operate on slices of one larger array), you should unpack a generator expression of calls to np.copy
# a is the numpy array to be copied
b, c, d, e, f, g = (np.copy(a) for _ in range(6))
Make sure that the number of copies being made (6 or 7 in the examples above) is accurate.
Upvotes: 2