Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse all booleans in the list in python? [duplicate]

Tags:

python

list

I want to reverse all my booleans in the list like this:

a=[True,False,True]

to this:

b=[False,True,False]

I tried

not a

But it gives only False to me.

like image 301
Ivan Pudyakov Avatar asked Nov 29 '25 00:11

Ivan Pudyakov


2 Answers

You could use list comprehension and not all the items

a=[True,False,True] 
b=[not c for c in a]

not a provided False due to the fact it checks list is empty since it isn't returns True so it is converted into false

a=[True]
not a
False
a=[False]
not a
True
like image 110
The6thSense Avatar answered Nov 30 '25 13:11

The6thSense


You can do this with list comprehension:

a = [True, False, True]
b = [not c for c in a]

What this does is basically analogous to:

a = [True, False, True]
b = []
for bool in a:
    b.append(not bool)

Or more generally:

new_list = [expression for item in a_list]

is essentially the same as:

new_list = []
for item in a_list:
    new_list.append(expression)

where expression can contain item

The reason your version doesn't work is that not can only operate on booleans and will implicitly convert anything passed to it to a boolean. A non-empty list results in True and applying not to that gives you False

like image 43
overactor Avatar answered Nov 30 '25 14:11

overactor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!