Skip to content Skip to sidebar Skip to footer

Swapping Two Elements Between Two Lists In Python

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

Solution 1:

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]))

Solution 2:

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.

Solution 3:

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

Post a Comment for "Swapping Two Elements Between Two Lists In Python"