10

Possible Duplicate:
The tilde operator in Python

What does the squiggle i.e. ~ operator do in Python?

(This is probably Python 101 for most, but I came across ~ in code and had no idea what it was, and it took me a surprising amount of research to figure it out, so hopefully this Q&A can help someone down the road.)

Community
  • 1
  • 1
Ghopper21
  • 10,287
  • 10
  • 63
  • 92
  • In general, the place to look for this sort of thing is directly in the language reference. – Marcin Aug 02 '12 at 16:32
  • It "flips the bits" of an integral value. The same operator exists in C, C++, Java, etc. – paulsm4 Aug 02 '12 at 16:33
  • Indeed, that's the first thing I did. I searched for ~ in the python docs. Which came up with nothing. I think the squiggle character messes with searches. – Ghopper21 Aug 02 '12 at 16:34
  • But then, why do you think it will be found on SO with that title? ;) – Felix Kling Aug 02 '12 at 16:34
  • this symbol is called [tilde](http://en.wikipedia.org/wiki/Tilde), next time it will be easier to search for `tilde operator python` in your favorite search engine – zenpoy Aug 02 '12 at 16:35
  • 2
    To help figure out what to google for punctuation, you can type things like `help('~')` at the prompt. This brings up a table, and searching for `~` reveals it's a "bitwise NOT" operator. After that, searching is easy. – DSM Aug 02 '12 at 16:36
  • Ah yes, it is essentially a duplicate of that. The issue is with discovering the answer. I did look around SO for an answer, but only searched for "squiggle" not "tilde". – Ghopper21 Aug 02 '12 at 16:37
  • Good point about searching on SO, added "squiggle" to title. – Ghopper21 Aug 02 '12 at 16:40

1 Answers1

13

It's the unary bitwise invert operator.

The unary ~ (invert) operator yields the bitwise inversion of its plain or long integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ghopper21
  • 10,287
  • 10
  • 63
  • 92