Swapping 1 with 0 and 0 with 1 in a Pythonic way

Solution 1:

This isn't pythonic, but it is language neutral. Often val = 1 - val is simplest.

Solution 2:

The shortest approach is using the bitwise operator XOR.

If you want val to be reassigned:

val ^= 1

If you do not want val to be reassigned:

val ^ 1

Solution 3:

Since True == 1 and False == 0 in python,

you could just use var = not var

It will just swap it.