Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flipping the boolean values in a list Python

Tags:

python

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?

like image 378
smilingbuddha Avatar asked May 21 '12 00:05

smilingbuddha


People also ask

How do you get the opposite of a boolean value?

And the "not" ( ! ) operator returns the opposite of the boolean value to its right. That is, true becomes false and false becomes true .

How do you change true to false in Python?

You can convert True and False to strings 'True' and 'False' with str() . Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .


Video Answer


2 Answers

It's easy with list comprehension:

mylist  = [True , True, False]  [not elem for elem in mylist] 

yields

[False, False, True] 
like image 147
Levon Avatar answered Sep 16 '22 15:09

Levon


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.

like image 22
Steven Matz Avatar answered Sep 17 '22 15:09

Steven Matz