Learn Statistics with NumPy quiz

So, I am working on the quiz for ‘Introduction to Numpy’ and confused about the ‘correct answer vs my selected answer’ pictured below. If I understood this and previous lessons correctly and there is certainly a chance I didn’t, the logical operator ’ | ’ should return values a > 15 or a < 5 which I understand could achieve the results.

My question however is why using the ‘&’ operator would not also be correct. Based upon the statement at the bottom of the screen I would guess that this is a typo and the choice was intended to read a[(a > 15) & (a < 15)] which would make sense and render this post moot.

Am I incorrect in this assumption?

https://www.codecademy.com/paths/data-science/tracks/intro-statistics-numpy/modules/dspath-intro-numpy/quizzes/learn-numpy-introduction-quiz-i

I’d agree with you that the statement at the bottom is a bit wrong. It does not match the given code.

However, the answer selected would be wrong even as it’s written in the code-

The ampersand (&) is used for logical AND which would return True only if both values are True (which would be on an index by index basis for this query).
a < 5 would return a boolean array where the index of each of the elements (4, 3, 2) would be True, others are False.
a > 15 would return a boolean array where the index of each of the elements (18, 22) would be True, others are False.

I think your issue is assuming these values are returned, they aren’t. If you evaluated that expression numpy would return a boolean array with the same size as the original array.

Quick example of how this works (you can test the full array yourself)-

nums = np.array((1, 2, 3))
print(nums == 3)
[False False True  # you get a boolean array out
# you could get the number out(but this does not happen in the given example)-
print(nums[nums == 3])  # filters out the values which evaluate to False
[3]  # note this is an array not a list, despite the similar print output

# In original code you'd still have to concatenate the two and fix the order...

The expression a > 15 & a < 5 for the given array then returns an array which is False at every element.

a[[False, False,  False... etc etc
# This will return an empty array because there are no elements...
# which are True in both arrays (how logical AND operates)

The exact values in the error statement given are wrong but the result is the same, an empty array. It probably should be flagged up anyway.

Thank you for that explanation, I can see where my thinking went off on a day cruise.