What explains the difference in behavior of boolean and bitwise operations on lists vs numpy.arrays?
I‘m getting confused about the appropriate use of the ‘&
‘ vs ‘and
‘ in python, illustrated in the following simple examples.
mylist1 = [True, True, True, False, True]
mylist2 = [False, True, False, True, False]
>>> len(mylist1) == len(mylist2)
True
# ---- Example 1 ----
>>>mylist1 and mylist2
[False, True, False, True, False]
#I am confused: I would have expected [False, True, False, False, False]
# ---- Example 2 ----
>>>mylist1 & mylist2
*** TypeError: unsupported operand type(s) for &: ‘list‘ and ‘list‘
#I am confused: Why not just like example 1?
# ---- Example 3 ----
>>>import numpy as np
>>> np.array(mylist1) and np.array(mylist2)
*** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
#I am confused: Why not just like Example 4?
# ---- Example 4 ----
>>> np.array(mylist1) & np.array(mylist2)
array([False, True, False, False, False], dtype=bool)
#This is the output I was expecting!
This answer, and this answer both helped me understand that ‘and‘ is a boolean operation but ‘&‘ is a bitwise operation.
I was reading some information to better understand the concept of bitwise operations, but I am struggling to use that information to make sense of my above 4 examples.
Note, in my particular situation, my desired output is a newlist where:
len(newlist) == len(mylist1)
newlist[i] == (mylist1[i] and mylist2[i]) #for every element of newlist
Example 4, above, led me to my desired output, so that is fine.
But I am left feeling confused about when/how/why I should use ‘and‘ vs ‘&‘. Why do lists and numpy arrays behave differently with these operators?
Can anyone help me understand the difference between boolean and bitwise operations to explain why they handle lists and numpy.arrays differently?
I just want to make sure I continue to use these operations correctly going forward. Thanks a lot for the help!
Numpy version 1.7.1
python 2.7
References all inline with text.
EDITS
1) Thanks @delnan for pointing out that in my original examples I had am ambiguity that was masking my deeper confusion. I have updated my examples to clarify my question.
True
in a position that‘sFalse
in the first list: Boolean logic dictates aFalse
output at that position, but you‘ll get aTrue
. – user395760 Mar 25 ‘14 at 21:22np.bitwise_and()
andnp.logical_and()
and friends to avoid confusion. – Dietrich Mar 25 ‘14 at 21:54mylist1 and mylist2
does not output the same result asmylist2 and mylist1
, since what is being returned is the second list as pointed out by delnan. – user2015487 Feb 16 ‘16 at 17:58