0
0
NumPydata~10 mins

np.expand_dims() and np.squeeze() in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a new axis to the array using np.expand_dims.

NumPy
import numpy as np
arr = np.array([1, 2, 3])
new_arr = np.expand_dims(arr, axis=[1])
print(new_arr.shape)
Drag options to blanks, or click blank then click option'
A2
B1
C0
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=0 adds the new axis at the start, changing shape to (1, 3).
Using axis=2 is invalid for 1D array.
2fill in blank
medium

Complete the code to remove single-dimensional entries from the shape using np.squeeze.

NumPy
import numpy as np
arr = np.array([[[1], [2], [3]]])
squeezed_arr = np.squeeze(arr, axis=[1])
print(squeezed_arr.shape)
Drag options to blanks, or click blank then click option'
A-1
B1
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to squeeze axis 1 which has size 3 causes an error.
Not specifying axis removes all single dimensions.
3fill in blank
hard

Fix the error in the code by choosing the correct axis to expand.

NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
new_arr = np.expand_dims(arr, axis=[1])
print(new_arr.shape)
Drag options to blanks, or click blank then click option'
A2
B3
C-1
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=3 causes an IndexError because the array has only 2 dimensions.
Using axis=1 changes shape differently than expected.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Blen(word) > 3
Cword.startswith('a')
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as the value instead of its length.
Using a condition unrelated to length.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = { [1]: [2] for word in words if [3] }
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Clen(word) > 3
Dword.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase instead of uppercase for keys.
Not filtering words by length.