# NumPy Examples: Forty-Five Practice Questions To Make You an Expert

Have you learned some NumPy, but now your learning has stalled because you don’t have any practice questions or exercises to review what you’ve learned?

This practice set of forty-five NumPy examples features NumPy questions and problems in varying degrees of difficulty. The exercises to challenge you are all in this article, but you’ll also find a link to the solution set at the end to compare your answers.

This practice set of NumPy challenges is part of our ongoing Python Practice Series. It features several questions that I worked on recently to review and improve my knowledge of NumPy — the excellent, high-performance n-dimensional array library that is a core pillar of the Python data science stack. These questions and exercises range from those that I could get right or code off the top of my head to challenging questions that I had no idea about when I worked on them (or made mistakes on the first time I tried). So don’t feel bad if some of these are hard, or you can’t finish all of them. That said, they will be simpler if you have some background in NumPy. If you need some materials for making a start on NumPy and Python data science, see our article, How to Practice Python: Data Science and Pandas.

For those I didn’t know the answer to, I used a combination of Google and The NumPy API Reference to try to work out the solution, so yes, you should research these if you want to practice! The exercises selected here cover many of the features of NumPy, but it’s not meant to be exhaustive. For example, the linear algebra features in `numpy.linalg` package are not covered.

In the exercises that follow, any unqualified references to an “array” mean a NumPy array, not a native Python array. References to “np” refer to the NumPy package in the usual way it is aliased: “`import numpy as np`“. Good luck, and let me know how it goes!

## Creating Simple One-Dimensional Arrays

NumPy has several functions that will return an n-Dimensional array. These exercises ask you to recall these functions to create simple (1-dimensional) arrays.

1. Using a NumPy function, how would you create a one dimensional NumPy array of the numbers from 10 to 100, counting by 10?
2. How could you do create the same NumPy array using a Python range and a list?
3. What happens if you pass no arguments to the np.array()?
4. How might you create a NumPy array of the capital letters, A-Z?
5. How would you create a ten-element array of all zeros?
6. What would the data type of such an array be?
7. How would you find the data type given in #6.
8. What function would return the same number of elements, but of all ones?
9. How could you create a ten element array of random integers between 1 and 5 (inclusive)?
10. How can you create a normal distribution of 10 numbers, centered on 5?
11. What code would create an array of 10 random numbers between zero and one?

## Creating and Using Multidimensional arrays

In this section, we move past one-dimensional arrays. As a reminder, many of the same functions that we used to create one-dimensional arrays select either a single scalar value for the number of elements to create or a tuple representing the shape of the array in higher dimensions.

1. Consider the code: `np.ones(3,5)`. Does this A) create an array of three arrays containing five elements each or B) create an array of five arrays containing three elements each?
2. Consider an array named “`myarray`” that is displayed as in the block below. What value does the code `myarray[1,2]` return? A) 10 B) 7.
``````# myarray:

array([[ 1,  2,  3,  4],
[ 5,  6,  7,  8],
[ 9, 10, 11, 12]])``````
1. Given `myarray` as shown above, what is the value of `myarray.ndim`?
2. An array of three arrays of four elements each like this has twelve elements, of course. How could you create a new array consisting of two arrays of six elements each?
3. Given `myarray` from #13, and the code `x = myarray`, what would `x[0,0] == 42` do?
4. How could you create a two-dimensional, 3 x 4 array (three arrays of four elements each) with random numbers from 1 to 10?
5. How could you create an array of the same size as #17, filled with zeros
6. Given this code:
``````z_list = [z for z in range(0,5)]
y_list = [z_list for y in range(0,4)]
x_list = [y_list for x in range(0,3)]

x_array = np.array(x_list)``````

What would x_array.shape() return?

1. Given `x_array` from #19, what is the value for `x_array.ndim`?
2. Given an array, named `"arr`“, that looks like:
``````array([[0, 1, 2],
[3, 4, 5]])``````

How could you display an array that looks like:

``````array([[0, 3],
[1, 4],
[2, 5]])``````

## Indexing and Slicing Two-Dimensional Arrays

NumPy arrays support indexing and slicing across using scalars and tuples. For questions 22-28, use the following array, assigned to the variable, four_by_five. Assume that the rows are the “outer” arrays of five elements each and that the nth element within all the rows is a column:

``````# four_by_five:

array([[ 1,  2,  3,  4,  5],
[ 6,  7,  8,  9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]])``````
1. Write an expression to return the first row. (It will be a five-element array).
2. Write an expression to return the last row. (It will be a five-element array).
3. What does four_by_five[2,3] return?
4. What does four_by_five[3,2] return?
5. How could you return the first column? It will be a (four-element array ending with 16.)
6. What does four_by_five[:, 3:5] return?
7. Write an expression to return the last two columns of the middle two rows.

## Vectorized Operations

Vectorized operations are implemented in NumPy so that many mathematical and logical functions operate across the whole array. These vectorized operations act on every array element without writing a Python loop. The most common ways to do this are to combine the array with itself, with an array of the same shape, or with a scalar value.

To keep it simple, let’s use a small one-dimensional array to begin. For exercises # 28-JCL TODO, use the following definitions:

``````one_dim = np.arange(1,6)
one_dim

# Output
array([ 1,  2,  3,  4,  5])``````
1. What would be the result of` one_dim * 2` ?
2. What would be returned by this expression: `one_dim + np.arange(5, 0, -1)` ?
3. How many zeros are in the array returned by `one_dim - one_dim` ?
4. What is the result of `one_dim > 2` ?
5. For NumPy arrays, logical operations are done with the operators “`&`” and “`|`“, rather than the usual Python “and” and “or”. Given that, what would be the result of this expression?
`(one_dim > 4) | (one_dim == 1)`
6. What is the result of this expression:
`-one_dim`
7. `np.absolute` take the absolute value of each element. Given that, what would the result be of the following expression:
`np.absolute(-(one_dim[3:])`
8. This exercise and #36 deal with sequence functions, which operate on the whole array rather than per-element. What is returned by `one_dim.sum()` ?
9. Break out those pictures of the unit circle for this one, for some trigonometry so simple a history major can do it! (I should know).

As background, we can round numbers to a decimal precision using `np.around(arr, num_decimals)`, and get the sine of an angle (in radians) using `np.sin`. So with that, given the following:

`arr = np.array([0., .5, 1.0, 1.5, 2.0]) * np.pi`

What are the values for:

`np.around(np.sin(arr), 0)`
10. For the defined above in #36, what are the values for:

`np.around(np.cos(arr), 0)`

## Working with Files

1. You’re asked to save the following two arrays as is to a file, “data.npz”. The arrays should be named as they are here in the file. How could you do it?
``````people = np.array(["John", "Jenniffer", "Helen", "Miryam"])
languages = np.array([2, 2, 1, 1])``````
1. Assuming you saved the file, “data.npz”, in #38, how could you reload the arrays into two new variables: `people2` and `languages2`?
2. Given

`arr = np.arange(1,13).reshape(3,4)`

How could you save it to a CSV file, “myrray.csv”.
3. Given the CSV file saved in #40, how could you load it back into a variable, `arr2`?

## NumPy String Functions

Since you’ve been working hard on these exercises, let’s relax a little with some simple character-oriented (string) functions, from the `np.char` package. These are vectorized (element-wise) versions of the Python standard library functions. Proving that every Python blog gets around to the Lumberjack Song eventually, here’s the NumPy array we’ll use for the problems in this section:

``````lumberjack = np.array("I'm a lumberjack and I'm OK I sleep all night and I work all day".split(" "))
lumberjack

# Output
array(["I'm", 'a', 'lumberjack', 'and', "I'm", 'OK', 'I', 'sleep', 'all',
'night', 'and', 'I', 'work', 'all', 'day'], dtype='<U10')``````
1. What would you expect the value of` np.char.capitalize(lumberjack)` to be?
2. How could you surround each string with an initial and final asterisk character (*)?
3. The function, `np.where`, can be used to create an array of indexes that can be used to index into the original array to subset an array based on a condition. Given that background, can you evaluate the following?
``lumberjack[np.where(np.char.str_len(lumberjack) >=5)]``

## View The Solutions

Have you tried these exercises? Were they all too easy, or were some of them impossibly difficult to solve?

Well, either way, I’m delighted to announce the launch of a very new companion site to this one where we can publish the source code and solutions from time to time. And with that, here’s our very first link to that site. (Even just viewing the inaugural link below means you’re one of the cool kids).

This site uses Akismet to reduce spam. Learn how your comment data is processed.