Flipping the boolean values in a list Python

It's easy with list comprehension:

mylist  = [True , True, False]

[not elem for elem in mylist]

yields

[False, False, True]

The unary tilde operator (~) will do this for a numpy.ndarray. So:

>>> import numpy
>>> mylist = [True, True, False]
>>> ~numpy.array(mylist)
array([False, False, True], dtype=bool)
>>> list(~numpy.array(mylist))
[False, False, True]

Note that the elements of the flipped list will be of type numpy.bool_ not bool.


>>> import operator
>>> mylist  = [True , True, False]
>>> map(operator.not_, mylist)
[False, False, True]

Numpy includes this functionality explicitly. The function "numpy.logical_not(x[, out])" computes the truth value of NOT x element-wise.

import numpy
numpy.logical_not(mylist)

http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.logical_not.html (with same examples)

Example:

import numpy
mylist  = [True , True, False]
print (mylist)

returns [True, True, False]

mylist=numpy.logical_not(mylist)
print (mylist)

returns [False False True]

Tags:

Python