0

In python, I have numpy arrays a0, a1, and a2, each of which refer to different contents. I want to shift the relations between the reference names and the referred objects, so that a2 will now point to the content pointed by a1 before, and a1 will now point to the content pointed by a0 before. Then, I want to let a0 to point to a new content.

To be more specific, I want to do something like this:

import numpy as np
a2=np.array([1,2,3,4])
a1=np.array([10,20,30,40])
a0=np.array([8,8,8,8]) 
a2=a1
a1=a0
# I want to assign new values to a0[0], a0[1], .., without affecting a1. 

Can I do it without copying values (e.g. by np.copy) and without memory reallocation (e.g. by del and np.empty)?

2
  • Why do you need to reuse the a0 array? And where do the new values come from? Commented Nov 8, 2018 at 20:29
  • What it comes down to is that you want both an unchanged a0 array, and a modified version of it. The fact that you are reusing the names ('shifting') doesn't matter. Commented Nov 8, 2018 at 20:44

2 Answers 2

2

Use tuple unpacking to exchanging values kindaof like the a,b=b,a

In [183]: a2=np.array([1,2,3,4])
     ...: a1=np.array([10,20,30,40])
     ...: a0=np.array([8,8,8,8]) 
     ...: 
     ...: 

In [184]: 


In [185]: a2,a1=np.copy(a1),np.copy(a0)

In [186]: a0
Out[186]: array([8, 8, 8, 8])

In [187]: a1
Out[187]: array([8, 8, 8, 8])

In [188]: a2
Out[188]: array([10, 20, 30, 40])

You are free to point a0 where ever you want and i dont think you can create get away with changing a0 and not affecting a1 without np.copy or something else like copy.deepcopy

Sign up to request clarification or add additional context in comments.

1 Comment

By that a0 and a1 will point to the same contend in memory, so changing a0 will also change a1. Eventually you want to discard a2 and create a new array so I thing there is no way around copying the content of a0 you want to keep.
1

What are you asking is not possible without making a copy of a0, otherwise a0 and a1 will be pointing to the same object and changing a0 will change a1. So you should do this:

a2 = np.array([1,2,3,4])
a1 = np.array([10,20,30,40])
a0 = np.array([8,8,8,8]) 

a2 = a1
a1 = a0.copy()

# let's change a0
a0[0] = 9

# check
a0
Out[31]: array([9, 8, 8, 8])

a1
Out[32]: array([8, 8, 8, 8])

a2
Out[33]: array([10, 20, 30, 40])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.