What does the operator ^= do in python?

276 views Asked by At

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.

1

There are 1 answers

0
TruBlu On

This is the bitwise XOR operator.

per your example, let each row represent iteration i in the for loop.

  1. 0^1 xor: 1
  2. 1^2 xor: 3
  3. 3^3 xor: 0
  4. 0^4 xor: 4
  5. 4^5 xor: 1

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)