You can also do this by old swaping method using indexing and loop if both list have same length. This is kind of old school but will help in understanding indexing
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
b = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for i in range(0, len(a)):
a[i] = a[i] + b[i]
b[i] = a[i] - b[i]
a[i] = a[i] - b[i]
print(a)
print(b)
This will give the output as :
[0,9,8,7,6,5,4,3,2,1]
[1,2,3,4,5,6,7,8,9,0]
Or It can also be done using Xor. Xor operator is a bitwise operator which do the Xor operation between the operands for example.
a = 5 #0b101
b = 4 #0b100
c = a ^ b #0b001
Here 0b101
is a binary representation of 5 and 0b100
is a binary representation of 4 and when you Xor these you will the ouput as 0b001
i.e 1 . Xor return 1 output results if one, and only one, of the inputs to is 1. If both inputs are 0 or both are 1, 0 output results.
We can swap a two variables using Xor for eg:
a = 5 # 0b0101
b = 9 # 0b1001
a = a ^ b # Xor (0b0101, 0b1001) = 0b1100 (12)
b = a ^ b # Xor (0b1100, 0b1001) = 0b0101 (5)
a = a ^ b # Xor (0b1100, 0b0101) = 0b1001 (9)
print("a = {} and b = {}".format(a, b))
The Output will be a = 9 and b = 5
Similarly we can also swap two list by doing Xor operation on there items for eg:
a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ]
b = [ 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
for i in range(0, len(a)) :
a[i] = a[i] ^ b[i]
b[i] = a[i] ^ b[i]
a[i] = a[i] ^ b[i]
print(a)
print(b)
Output:
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
Lets Take another scenario, What if we need to swap the items within the list for eg:
we have a list like this x = [ 13, 3, 7, 5, 11, 1 ]
and we need to swap its item like this x = [ 1, 3, 5, 7 , 11, 13 ]
So we can do this by Using two bitwise operators Xor ^
and Compliments ~
Code :
# List of items
a = [ 13, 3, 7, 5, 11, 1 ]
# Calculated the length of list using len() and
# then calulated the middle index of that list a
half = len(a) // 2
# Loop from 0 to middle index
for i in range(0, half) :
# This is to prevent index 1 and index 4 values to get swap
# because they are in their right place.
if (i+1) % 2 is not 0 :
#Here ~i means the compliment of i and ^ is Xor,
# if i = 0 then ~i will be -1
# As we know -ve values index the list from right to left
# so a [-1] = 1
a[i] = a[i] ^ a[~i]
a[~i] = a[i] ^ a[~i]
a[i] = a[i] ^ a[~i]
print(a)
So Output will be [1, 3, 5, 7, 11, 13]