Flipping the boolean values in a list Python

Question:

I have a boolean list in Python

mylist  = [True , True, False,...]

which I want to change to the logical opposite [False, False, True , ...]
Is there an inbuilt way to do this in Python (something like a call not(mylist) ) without a hand-written loop to reverse the elements?

Asked By: smilingbuddha

||

Answers:

It’s easy with list comprehension:

mylist  = [True , True, False]

[not elem for elem in mylist]

yields

[False, False, True]
Answered By: Levon

Why not just use a simple list comprehension?

mylist[:] = [not x for x in mylist]
Answered By: mVChr
>>> import operator
>>> mylist  = [True , True, False]
>>> map(operator.not_, mylist)
[False, False, True]
Answered By: John La Rooy

I would do it the way everybody else is saying, but for sake of documenting alternatives, you could also do

import operator
myList = map(operator.not_, myList)
Answered By: Tyler Crompton

what about the following

>>> import numpy
>>> list(numpy.asarray(mylist)==False)
Answered By: Gerben

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.

Answered By: Steven Matz

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]

Answered By: Marcel Flygare

numpy.invert is another nice option:

x = [False, True, True] 
not_x = np.invert(x) # [True, False, False]
Answered By: gebbissimo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.