In the book "Fluent Python" the example 10.11 goes like this:
n = 0
for i in range(1, 6):
n ^= i
1 is the value of n at the end of the loop.
I'd really like to know how this ^= operator works.
In the book "Fluent Python" the example 10.11 goes like this:
n = 0
for i in range(1, 6):
n ^= i
1 is the value of n at the end of the loop.
I'd really like to know how this ^= operator works.
This is the bitwise XOR operator.
per your example, let each row represent iteration i in the for loop.
Let us look at row 2, where i=2. Assume we are using binary rather than base 10.
1^2 is equivalent to the following
0001 = 1 (base 10)
XOR
0010 = 2 (base 10)
Returns
0011 = xor result = 3 (base 10)