Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of booleans comparison gives strange results

I try:

[True,True,False] and [True,True,True]

and get [True, True True]

but

[True,True,True] and [True,True,False]

gives

[True,True,False]

Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want

[True,True,False] and [True,True,True]

to evaluate to

[True,True,False]
like image 407
virati Avatar asked Oct 15 '12 15:10

virati


People also ask

What is boolean indexing Python?

In its simplest form, boolean indexing behaves as follows: Suppose x is an -dimensional array, and ind is a boolean-value array of the same shape as x . Then x[ind] returns a 1-dimensional array, which is formed by traversing x and ind using row-major ordering.

How do you get boolean output in Python?

Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.


1 Answers

Others have explained what's going on. Here are some ways to get what you want:

>>> a = [True, True, True]
>>> b = [True, True, False]

Use a listcomp:

>>> [ai and bi for ai,bi in zip(a,b)]
[True, True, False]

Use the and_ function with a map:

>>> from operator import and_
>>> map(and_, a, b)
[True, True, False]

Or my preferred way (although this does require numpy):

>>> from numpy import array
>>> a = array([True, True, True])
>>> b = array([True, True, False])
>>> a & b
array([ True,  True, False], dtype=bool)
>>> a | b
array([ True,  True,  True], dtype=bool)
>>> a ^ b
array([False, False,  True], dtype=bool)
like image 98
DSM Avatar answered Sep 29 '22 23:09

DSM