Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the ~ operator do in Python [duplicate]

This is my attempt at understanding what it does:

>>> ~
SyntaxError: invalid syntax
>>> print ~
SyntaxError: invalid syntax
>>> ~ = cheese
SyntaxError: invalid syntax
>>> ~ = "21"
SyntaxError: invalid syntax
>>> 2 ~ 1
SyntaxError: invalid syntax
>>> ~ = "w"
SyntaxError: invalid syntax
>>> a = "w"
>>> a
'w'
>>> print ~8
-9
>>> print ~w

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    print ~w
NameError: name 'w' is not defined
>>> print ~"w"

It seems to only work with numbers, so an explanation and a link to some documentation would be very helpful.

like image 723
Games Brainiac Avatar asked Jul 04 '26 22:07

Games Brainiac


1 Answers

~ is a unary operator (i.e. it takes only one argument) which calculates the bitwise inverse of its argument. The result is -x - 1, because in Two's complement representation, -x is the same as inverting all bits and then adding one.

like image 123
phihag Avatar answered Jul 07 '26 10:07

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!