I am starting a new project to work through problems from the book Conceptual Programming with Python.1 I saw a video of Professor Thorsten discussing recursion 2 and enjoyed his explanation. After watching a few more videos of Profesor Thorsten, I bought his book.

The first problem, given the code below, what happens when you replace and with &? The authors challenge the reader to solve the problem without executing the code.

def isEven(n):
    return type(n) == int and n % 2 == 0

The desired specification is to return True if the input is even and False otherwise. Replacing and with & will break the specification because and in python is a short circuit, boolean expression where the second expression is only evaluated if the first expression evaluates as True.

To verify my understanding, I searched for the difference between the two operators. Within the first link, I found a case that tripped me up. The example is shown below, adopted from the stack overflow question and (boolean) vs & (bitwise) - Why difference in behavior with lists vs NumPy arrays? 3

mylist1 = [True,  True,  True, False,  True]
mylist2 = [False, True, False,  True, False]

mylist1 and mylist2
[False, True, False, True, False]
# I would have expected [False, True, False, False, False]

Coming from MATLAB®, I expected the same result expressed by the OP. The confusion lies with

  1. remembering and is not bitwise
  2. non-empty list evaluating to True

Thus the entire expression mylist1 and mylist2 results in mylist2.


Post History

References

  1. “Conceptual Programming with Python - Thorsten Altenkirch and Isaac Triguero. Accessed 26 Aug. 2020.” 

  2. “Recursion “Super Power” (in Python) - Computerphile - YouTube. Accessed 26 Aug. 2020.” 

  3. “Python - and (Boolean) vs & (Bitwise) - Why Difference in Behavior with Lists vs Numpy Arrays? Stack Overflow Accessed 26 Aug. 2020.”