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]

Eric Han
  • 45
  • 2
  • 10

3 Answers3

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]))
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
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.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
-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

kchawla-pi
  • 408
  • 5
  • 12