Take the 2-minute tour ×

What's the usage of the tilde operator in Python?

One thing I can think about is do something in both sides of a string or list, such as check if a string is palindromic or not:

def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) / 2)) 

Any other good usage?

share|improve this question
Note that unary complement operator ~ implemented by the special method __invert__ is unrelated to the not operator, which logically negates the value returned by __bool__ (or __nonzero__ in 2.x). It's also unrelated to the - unary negation operator, implemented by __neg__. For example ~True == -2, which isn't False or false, and -False == 0, which is still false. –  eryksun Nov 29 '11 at 4:54

2 Answers 2

up vote 47 down vote accepted

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
>>> x = Foo()
>>> operator.invert(x)
>>> ~x

Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)

share|improve this answer
Good explanation, but a word of caution - all the safety disclaimers for operator overloading apply here - it's not a good idea, unless it fits the bill just perfectly. –  Eli Bendersky Nov 29 '11 at 3:09
Eli's feedback has been incorporated into the answer in the final paragraph. –  wberry Apr 2 '12 at 15:22

~ is the bitwise complement operator in python which essentially calculates -x - 1

So a table would look like

i  ~i  
0  -1
1  -2
2  -3
3  -4 
4  -5 
5  -6

So for i = 0 it would compare s[0] with s[len(s) - 1], for i = 1, s[0] with s[len(s) - 2].

As for your other question, this can be useful for a range of bitwise hacks.

share|improve this answer

Your Answer


