Better way to negate a boolean list?

S

Steve Holden

Paddy said:
Hi,

Is there any better (shorter) way to negate a boolean list than:
negated_boolean_list = [not elem for elem in boolean_list]
?

I tried:
map(not, boolean_list)
but it seems that "not" is not a function.

Thanks in advance,

David

Try [not x for x in boolean_list]
This six-character shortening by renaming the comprehension's bound
variable was a joke, right?

regards
Steve
 
S

Stargaming

but it seems that "not" is not a function.[/QUOTE]

`not` is not a function, indeed. It is a keyword, allowing you to write
``not x`` instead of ``not(x)``.

You can of course write a function that just returns its input negated
and pass this function to `map`. Since Python comes with batteries
included, there is such a function already in the `operator module
<http://docs.python.org/lib/module-operator.html>`_::

import operator
map(operator.not_, boolean_list)
# ^ underscore to distinguish from the keyword

Cheers,
 
P

Paddy

Paddy said:
Hi,
Is there any better (shorter) way to negate a boolean list than:
negated_boolean_list = [not elem for elem in boolean_list]
?
I tried:
map(not, boolean_list)
but it seems that "not" is not a function.
Thanks in advance,
David
Try [not x for x in boolean_list]

This six-character shortening by renaming the comprehension's bound
variable was a joke, right?
No,
Of course not!
It's much worse - I completely missed the line beginning negated_....
on
first and second reading.
I am indeed getting older, although I had thought I was way off my
dotage.

- Paddy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top