NumPy Tutorial NumPy Statistics NumPy References

NumPy - invert() function

The Bitwise NOT operator (~) is an unary operator which takes a bit pattern and performs the logical NOT operation on each bit. It is used to invert all of the bits of the operand. It is interesting to note that for any integer x, ~x is the same as -(x + 1).

Bit~ Bit

The example below describes how bitwise NOT operator works:

  528 -> 00000000000000000000001000010000 (in binary)
 -529 <- 11111111111111111111110111101111 (in binary) 

The NumPy invert() function computes the bitwise inversion, or bitwise NOT, element-wise. This ufunc implements the C/Python operator ~.


numpy.invert(x, out=None)


x Required. Specify the array to be operated. Only integer and boolean types are handled.
out Optional. Specify a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Return Value

Returns the result of bitwise NOT operation. This is a scalar if x is scalar.


In the example below, the invert() function is used to compute the bitwise NOT of a scalar.

import numpy as np

x = 528

#Bitwise NOT operation
y = np.invert(x)

#Displaying the result
print("y =", y)

The output of the above code will be:

y = -529


The invert() function can be used with an array where it computes the bitwise NOT of the array element-wise.

import numpy as np

x = np.array([[10, 20],[30, 40]])

#Bitwise NOT operation
y = np.invert(x)

#Displaying the result
print("y =")

The output of the above code will be:

y =
[[-11 -21]
 [-31 -41]]

❮ NumPy - Binary Operators