Python Forum

Full Version: NumPy Side Effects - HELP UNDERSTANDING
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I AM CURRENTLY ON CHAPTER 4 WITH DATACAMP. SO FAR, SO GOOD

HOWEVER, I AM TRYING TO UNDERSTAND THIS

Have a look at this line of code:

np.array([True, 1, 2]) + np.array([3, 4, False])
Can you tell which code chunk builds the exact same Python object? The numpy package is already imported as np, so you can start experimenting in the IPython

HOW DOES

np.array([True, 1, 2]) + np.array([3, 4, False])

=

np.array([4, 3, 0]) + np.array([0, 2, 2])

CAN SOMEONE EXPLAIN THIS IN SIMPLE TERMS PLEASE :-)
Python treats True like 1, and False like 0. Other than that, it's just summing the respective elements. It's much like this:
Output:
>>> def sum_elements(first_elements, second_elements): ... return [x + y for x, y in zip(first_elements, second_elements)] ... >>> sum_elements([True, 1, 2], [3, 4, False]) [4, 5, 2] >>> sum_elements([4, 3, 0], [0, 2, 2]) [4, 5, 2]
Also, please avoid writing in all caps, as it looks like you're shouting.
(Sep-16-2020, 10:08 PM)micseydel Wrote: [ -> ]Python treats True like 1, and False like 0. Other than that, it's just summing the respective elements. It's much like this:
Output:
>>> def sum_elements(first_elements, second_elements): ... return [x + y for x, y in zip(first_elements, second_elements)] ... >>> sum_elements([True, 1, 2], [3, 4, False]) [4, 5, 2] >>> sum_elements([4, 3, 0], [0, 2, 2]) [4, 5, 2]

Ahhh okay. Thank you for explaining :-)