You can also do this with the old swaping method, using indexing and looping if both lists are the same length. It's kind of an old school, but it helps to understand 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 a result like:
[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 with Xor. The Xor operator is a bitwise operator that performs the Xor operation between operands, for example.
a = 5
Here 0b101 is the binary representation of 5, and 0b100 is the binary representation of 4, and when you are XOR, you will be 0b001 ie 1. Xor returns 1 output if one and only one of the inputs is 1. If both inputs are 0 or both have result 1, 0. We can change two variables using Xor, for example:
a = 5
The output will be a = 9 and b = 5
Similarly, we can also swap two lists by doing an Xor operation there, for example:
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]
Let's take another scenario. What if we need to change the elements in the list, for example: we have a list like this x = [ 13, 3, 7, 5, 11, 1 ] , and we need to change it this way x = [ 1, 3, 5, 7 , 11, 13 ] . So we can do this using two bitwise operators Xor ^ and Compliments ~
The code:
Thus, the conclusion will be [1, 3, 5, 7, 11, 13]