Bird
Raised Fist0
NumPydata~20 mins

np.unique() for unique elements in NumPy - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
np.unique Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of np.unique() with return_counts
What is the output of this code snippet using np.unique() with return_counts=true?
NumPy
import numpy as np
arr = np.array([3, 1, 2, 3, 2, 1, 4])
result = np.unique(arr, return_counts=True)
print(result)
A(array([1, 2, 3, 4]), array([2, 1, 2, 2]))
B(array([1, 2, 3, 4]), array([1, 2, 2, 2]))
C(array([1, 2, 3, 4]), array([2, 2, 2, 1]))
D(array([1, 2, 3, 4]), array([1, 1, 1, 1]))
Attempts:
2 left
💡 Hint
Think about how many times each unique number appears in the array.
❓ data_output
intermediate
1:30remaining
Number of unique elements in a 2D array
How many unique elements are in this 2D numpy array?
NumPy
import numpy as np
arr = np.array([[1, 2, 2], [3, 1, 4], [4, 5, 5]])
unique_elements = np.unique(arr)
print(len(unique_elements))
A6
B4
C7
D5
Attempts:
2 left
💡 Hint
Count each distinct number in the whole 2D array.
❓ Predict Output
advanced
2:30remaining
Output of np.unique() with return_index and return_inverse
What is the output of this code using np.unique() with return_index=true and return_inverse=true?
NumPy
import numpy as np
arr = np.array([5, 3, 5, 2, 3])
unique, index, inverse = np.unique(arr, return_index=True, return_inverse=True)
print(unique, index, inverse)
A[2 3 5] [3 1 0] [2 1 2 0 1]
B]1 2 0 1 0[ ]0 1 3[ ]5 3 2[
C[2 3 5] [3 1 0] [0 1 0 2 1]
D[2 3 5] [3 1 0] [0 1 2 0 1]
Attempts:
2 left
💡 Hint
Remember that return_index gives the first occurrence index of each unique element, and return_inverse maps original elements to unique indices.
🔧 Debug
advanced
1:30remaining
Identify the error in np.unique() usage
What error will this code raise?
NumPy
import numpy as np
arr = np.array([1, 2, 3])
result = np.unique(arr, return_counts='yes')
print(result)
AValueError: invalid literal for int() with base 10: 'yes'
BTypeError: return_counts must be a boolean
CTypeError: 'str' object cannot be interpreted as an integer
DTypeError: return_counts must be a bool
Attempts:
2 left
💡 Hint
Check the expected type for the return_counts parameter.
🚀 Application
expert
3:00remaining
Using np.unique() to find duplicates in a large dataset
You have a large numpy array of integers. Which code snippet correctly identifies all elements that appear more than once?
A
unique, counts = np.unique(arr, return_counts=True)
duplicates = unique[counts > 1]
B
unique = np.unique(arr)
duplicates = [x for x in unique if arr.count(x) > 1]
Cduplicates = np.unique(arr[arr > 1])
D
unique, counts = np.unique(arr)
duplicates = unique[counts > 1]
Attempts:
2 left
💡 Hint
Use return_counts to get counts of each unique element.

Practice

(1/5)
1. What does the np.unique() function do when applied to a NumPy array?
easy
A. Returns the shape of the array
B. Returns the sum of all elements in the array
C. Returns the maximum value in the array
D. Returns all unique elements sorted from the array

Solution

  1. Step 1: Understand the purpose of np.unique()

    The function np.unique() extracts all different values from the input array and sorts them.
  2. Step 2: Compare with other options

    Options A, B, and D describe different functions like shape, sum, and max, which are not what np.unique() does.
  3. Final Answer:

    Returns all unique elements sorted from the array -> Option D
  4. Quick Check:

    np.unique() = unique sorted elements [OK]
Hint: np.unique() always returns sorted unique values [OK]
Common Mistakes:
  • Thinking it returns counts by default
  • Confusing with sum or max functions
  • Assuming it returns unsorted unique values
2. Which of the following is the correct syntax to get unique elements from a NumPy array arr?
easy
A. np.unique(arr)
B. arr.unique()
C. unique(arr)
D. np.arr.unique()

Solution

  1. Step 1: Recall the correct function call

    The correct way to call the unique function in NumPy is np.unique(arr).
  2. Step 2: Identify incorrect syntax

    Options A, B, and C are invalid because either the method does not exist on the array object or the function is not called from the NumPy module correctly.
  3. Final Answer:

    np.unique(arr) -> Option A
  4. Quick Check:

    Use np.unique(array) syntax [OK]
Hint: Always call unique as np.unique(array) [OK]
Common Mistakes:
  • Trying to call unique as a method on array
  • Forgetting the np. prefix
  • Using a non-existent unique() function without np
3. What is the output of the following code?
import numpy as np
arr = np.array([3, 1, 2, 3, 2, 1, 4])
result = np.unique(arr)
print(result)
medium
A. [4 3 2 1]
B. [3 1 2 4]
C. [1 2 3 4]
D. [1 1 2 2 3 3 4]

Solution

  1. Step 1: Apply np.unique() to the array

    The function extracts unique values from the array: 1, 2, 3, and 4.
  2. Step 2: Note the sorting behavior

    np.unique() returns these unique values sorted in ascending order: [1 2 3 4].
  3. Final Answer:

    [1 2 3 4] -> Option C
  4. Quick Check:

    Unique sorted values = [1 2 3 4] [OK]
Hint: np.unique() sorts unique values automatically [OK]
Common Mistakes:
  • Expecting original order instead of sorted
  • Including duplicates in output
  • Confusing with counts output
4. The following code is intended to print unique elements of arr but raises an error. What is the error?
import numpy as np
arr = np.array([5, 6, 5, 7])
result = arr.unique()
print(result)
medium
A. 'numpy.ndarray' object has no attribute 'unique'
B. SyntaxError: invalid syntax
C. TypeError: unique() missing 1 required positional argument
D. NameError: name 'unique' is not defined

Solution

  1. Step 1: Identify the method call on the array

    The code calls arr.unique(), but NumPy arrays do not have a method named unique().
  2. Step 2: Understand the correct usage

    The correct function is np.unique(arr), a function in the NumPy module, not a method of the array object.
  3. Final Answer:

    'numpy.ndarray' object has no attribute 'unique' -> Option A
  4. Quick Check:

    Arrays have no unique() method [OK]
Hint: np.unique() is a function, not an array method [OK]
Common Mistakes:
  • Calling unique() as a method on array
  • Forgetting to import numpy as np
  • Using wrong function name or syntax
5. Given a 2D NumPy array arr = np.array([[1, 2, 2], [3, 1, 4]]), which code correctly finds all unique elements in the entire array?
hard
A. np.unique(arr, axis=0)
B. np.unique(arr)
C. np.unique(arr, axis=1)
D. arr.unique()

Solution

  1. Step 1: Understand np.unique() on 2D arrays

    Calling np.unique(arr) flattens the array and returns all unique elements sorted.
  2. Step 2: Check axis parameter effects

    Using axis=0 or axis=1 returns unique rows or columns, not unique elements overall.
  3. Step 3: Identify invalid method call

    arr.unique() is invalid because arrays do not have a unique method.
  4. Final Answer:

    np.unique(arr) -> Option B
  5. Quick Check:

    np.unique(array) finds all unique elements [OK]
Hint: Use np.unique(arr) to get all unique elements in any array [OK]
Common Mistakes:
  • Using axis parameter expecting unique elements, but it returns unique rows/columns
  • Calling unique() as a method on array
  • Confusing unique elements with unique rows or columns