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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With