Published July 28, 2026
OK. This isn't actually today. I learned this on Sunday at PyOhio but it took me a bit of time to get to a computer to
be able to actually type it out. This post is about Python's unary operator for bitwise inversion ~. Before we get
into the fun part, let's talk about what a bitwise inversion is. The short version is that it flips all the bits so that
ones become zeros and the zeros become ones.
The best way to see this in Python is by using struct to look at the actual bytes:
>>> struct.pack('i', 0xff)
b'\xff\x00\x00\x00'
>>> struct.pack('i', ~0xff)
b'\x00\xff\xff\xff'
If we pack 0xff (255) we'll see that what we actually have is the 4 bytes 0xff000000. The bitwise inversion of that
is 0x00ffffff (16777215 as an unsigned 32 bit int or -256 as a signed one.) The bitwise inversion of a number, n, is
-(n + 1).
>>> ~0
-1
>>> ~1
-2
OK. Now that we have that basic thing covered we can get where this can be very useful in Python. As I'm sure you know
you can access a list via indices. So list[0] is the leftmost and list[1] is the second from the left. We can use
negative indices to go from the right, meaning that list[-1] is the rightmost and list[-2] is the second from the right.
>>> l
[0, 1, 2, 3, 4]
>>> l[0]
0
>>> l[1]
1
>>> l[-1]
4
>>> l[-2]
3
Now, we can combine these two things:
>>> for n in l:
... print(f'{n=} {~n=} {l[n]=} {l[~n]=}')
...
n=0 ~n=-1 l[n]=0 l[~n]=4
n=1 ~n=-2 l[n]=1 l[~n]=3
n=2 ~n=-3 l[n]=2 l[~n]=2
n=3 ~n=-4 l[n]=3 l[~n]=1
n=4 ~n=-5 l[n]=4 l[~n]=0
What this means is that we can use the unary binary inversion operator (~) to use a zero-based index to access lists
from the right side. Because list[~0] is the exact same as list[-1] we can use them interchangeably.
While using a ~ as part of the index might look a bit odd but I think it makes a lot more sense as a way to accurately
access list items from the right side. The simple consistency of using 0 for the first item, 1 for the second, and so
forth with the presence or absence of a ~ showing which side we're looking at truly improves list access.