How to index 1D numpy arrays?

Daily Data Science Puzzle

import numpy as np

# The fibonacci series
F = np.array([0, 1, 1, 2, 3, 5, 8])
F[::3] = 0

What is the output of this puzzle?
*Intermediate Level*

Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.

This puzzle demonstrates indexing in numpy arrays. You most likely know indexing for Python lists or strings. Indexing for numpy works in a similar way.

There are two interesting twists in this puzzle. First, we overwrite each third value of the numpy array with the concise expression F[::3] starting from the very first entry. Second, we print the sum of the first four values. As we have just overwritten the first and the fourth value, the sum is only 2.

Are you a master coder?
Test your skills now!

Related Video




Leave a Comment

Your email address will not be published. Required fields are marked *