Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Operator ^

Sets exactly the bit positions where the operands differ.

Version: Python 3.14; repository image, production runtime not attested

Syntax

left ^ right

Sets exactly the bit positions where the operands differ.

Use exclusive OR to toggle a collection of flags without disturbing the other bits. A one in the mask flips the corresponding bit of the value.

A second application of the same mask restores the starting integer. Sets give the same spelling a related meaning, producing members that occur on exactly one side.

Combining a mask with itself clears every bit.

Syntax

left ^ right

__xor__, __rxor__ · TypeError

Worked example

0b1010 ^ 0b0110 → 0b1100
x ^ x → 0
{1, 3} ^ {3, 5} → {1, 5}

set ^

For sets, ^ forms the symmetric difference, retaining elements present in exactly one operand. Common b drops out and a set compared with itself yields an empty result. A frozenset on the left preserves the frozenset result type.

before=frozenset({"a","b"})
after={"b","c"}
changed=before ^ after
assert changed=={"a","c"} and type(changed) is frozenset
assert before ^ before == frozenset()
assert before.symmetric_difference(["c"])=={"a","b","c"}

Examples

print(0b1100 ^ 0b1010)
print(0b1010 ^ 0b1010)

Result

6
0

Combining a mask with itself clears every bit.

Sources