Flipping the boolean values in a list Python

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

It's easy with list comprehension:

mylist  = [True , True, False]

[not elem for elem in mylist]

yields

[False, False, True]

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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]

Solution 5 - Python

numpy.invert is another nice option:

x = [False, True, True] 
not_x = np.invert(x) # [True, False, False]

Solution 6 - Python

Why not just use a simple list comprehension?

mylist[:] = [not x for x in mylist]

Solution 7 - Python

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)

Solution 8 - Python

what about the following

>>> import numpy
>>> list(numpy.asarray(mylist)==False)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsmilingbuddhaView Question on Stackoverflow
Solution 1 - PythonLevonView Answer on Stackoverflow
Solution 2 - PythonSteven MatzView Answer on Stackoverflow
Solution 3 - PythonJohn La RooyView Answer on Stackoverflow
Solution 4 - PythonMarcel FlygareView Answer on Stackoverflow
Solution 5 - PythongebbissimoView Answer on Stackoverflow
Solution 6 - PythonmVChrView Answer on Stackoverflow
Solution 7 - PythonTyler CromptonView Answer on Stackoverflow
Solution 8 - PythonGerbenView Answer on Stackoverflow