Challenge - 5 Problems
np.newaxis Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of adding a new axis to a 1D array
What is the shape of the array
b after adding a new axis using np.newaxis?NumPy
import numpy as np a = np.array([1, 2, 3]) b = a[:, np.newaxis] print(b.shape)
Attempts:
2 left
💡 Hint
Think about how adding a new axis in the second position changes the shape.
✗ Incorrect
Using
np.newaxis in the second position converts the 1D array of shape (3,) into a 2D array with shape (3, 1).❓ data_output
intermediate2:00remaining
Resulting array after adding new axis
What is the output of the array
b after adding a new axis?NumPy
import numpy as np a = np.array([4, 5, 6]) b = a[np.newaxis, :] print(b)
Attempts:
2 left
💡 Hint
Adding
np.newaxis at the start adds a new row dimension.✗ Incorrect
Using
np.newaxis at the start changes the shape from (3,) to (1, 3), making it a 2D array with one row.❓ visualization
advanced2:30remaining
Visualizing shape changes with np.newaxis
Which option correctly describes the shape change when adding
np.newaxis to a 2D array arr of shape (2, 3) as arr[:, :, np.newaxis]?NumPy
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) new_arr = arr[:, :, np.newaxis] print(new_arr.shape)
Attempts:
2 left
💡 Hint
Adding
np.newaxis at the end adds a new dimension at the last position.✗ Incorrect
The original array has shape (2, 3). Adding
np.newaxis as the third index adds a new dimension at the end, resulting in shape (2, 3, 1).🔧 Debug
advanced2:00remaining
Identify the error when using np.newaxis incorrectly
What error will this code raise?
NumPy
import numpy as np a = np.array([1, 2, 3]) b = a[np.newaxis, np.newaxis] print(b.shape)
Attempts:
2 left
💡 Hint
Check how many dimensions the original array has and how many indices are used.
✗ Incorrect
The original array is 1D with shape (3,). Using two
np.newaxis adds two new dimensions, resulting in shape (1, 1, 3). This is valid and does not raise an error.🚀 Application
expert3:00remaining
Using np.newaxis to prepare data for broadcasting
Given two arrays
a with shape (5,) and b with shape (3,), which option correctly uses np.newaxis to add dimensions so that a + b broadcasts to shape (5, 3)?NumPy
import numpy as np a = np.arange(5) b = np.arange(3) # Which option below correctly reshapes a and b for broadcasting?
Attempts:
2 left
💡 Hint
Broadcasting works when dimensions are compatible or equal to 1.
✗ Incorrect
Adding
np.newaxis to a as a[:, np.newaxis] changes shape from (5,) to (5, 1). Adding np.newaxis to b as b[np.newaxis, :] changes shape from (3,) to (1, 3). These shapes broadcast to (5, 3).