0

I'm trying to swap elements between two lists, and python doesn't seem to let that happen.

def swap(A,B,i,j):
    TEMP_B = B[j]
    B[j] = A[i]
    A[i] = TEMP_B
    return A,B

X = np.array([[1.25,3],[1.5,2],[2,2.75],[2.25,2],[2,0.5],[3.25,0.75],
[3.5,2.25],[4.25,0.75]])
Y = np.array([[2.75,3.5],[3.25,3],[4.5,2.75],[3.5,4.75]])
X,Y = swap(X,Y,1,1)
OUTPUT:::
Temp = [ 3.25  3.  ]
before swap
X[ 1 ]: [ 1.5  2. ]
Y[ 1 ]: [ 3.25  3.  ]
Temp = [ 1.5  2. ]
after swap
X[ 1 ]: [ 1.5  2. ]
Y[ 1 ]: [ 1.5  2. ]

I expect B[j] = old A[i] and A[i] = old B[j] However, only one of the items gets swapped.. Not sure what the problem is. This is the output it get:

I'm expecting X[1] = [3.25,3] but it comes out as [1.5,2]

9
  • 2
    How do you call swap? Post up the code of caller. Commented Dec 3, 2017 at 3:43
  • 3
    note that this is the same as A[i], B[j] = B[j], A[i] Commented Dec 3, 2017 at 3:44
  • Can you give an example of input output that yields that result? Commented Dec 3, 2017 at 3:46
  • Your function appears to be working. Here is an image of it swapping two items in a list. imgur.com/a/knanR Commented Dec 3, 2017 at 3:51
  • 2
    I confirm that it has to do with numpy.array. I could reproduce. And it only does it with 2D arrays. Commented Dec 3, 2017 at 3:56

3 Answers 3

2

You can use .copy() if working on NumPy arrays:

def swap(A,B,i,j):
    TEMP_B = B[j].copy()
    B[j] = A[i]
    A[i] = TEMP_B
    return A,B

Should work on 1d or 2d arrays.

A = np.arange(5)
B = np.arange(5, 10)
swap(A, B, 1, 1)
# (array([0, 6, 2, 3, 4]), 
#  array([5, 1, 7, 8, 9]))
Sign up to request clarification or add additional context in comments.

Comments

1

This does not come from your swap function that works with regular arrays It has to do with the fact that you are using numpy.array.

Here is a similar question I found.

You need to do TEMP_B = np.copy(B[j]) since Numpy copies data lazily.

3 Comments

Wait, I got someting wrong with the index but will fix
I feel it's different enough since I kind of struggled to adapt the other answer to swap between arrays instead of swaping in the same array. I don't use numpy a lot though.
I actually found the exact same one, it is a duplicate of stackoverflow.com/questions/14933577/…
-1
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c']

print(l1, l2)
l1[1], l2[2] = l2[2], l1[1]
print(l1, l2)

in essence:

list1[i], list2[j] = list2[j], list1[i]
a, b = b, a

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.