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
Shuffling Arrays with NumPy
📖 Scenario: You are working with a list of student IDs for a class. You want to randomly shuffle the order of these IDs to assign presentation slots fairly.
🎯 Goal: Learn how to shuffle a NumPy array to randomize the order of elements.
📋 What You'll Learn
Create a NumPy array with specific student IDs
Set a random seed for reproducibility
Shuffle the array using NumPy
Print the shuffled array
💡 Why This Matters
🌍 Real World
Randomly shuffling data is useful in experiments, games, and fair assignments like presentations or seating.
💼 Career
Data scientists often shuffle data to prepare for training machine learning models or to randomize samples.
Progress0 / 4 steps
1
Create the NumPy array
Import NumPy as np and create a NumPy array called student_ids with these exact values: 101, 102, 103, 104, 105.
NumPy
Hint
Use np.array() to create the array with the given numbers.
2
Set the random seed
Set the random seed to 42 using np.random.seed(42) to make the shuffle results reproducible.
NumPy
Hint
Use np.random.seed(42) before shuffling to get the same random order every time.
3
Shuffle the array
Use np.random.shuffle(student_ids) to shuffle the student_ids array in place.
NumPy
Hint
Call np.random.shuffle() with the array you want to shuffle.
4
Print the shuffled array
Print the student_ids array to see the shuffled order.
NumPy
Hint
Use print(student_ids) to display the shuffled array.
Practice
(1/5)
1. What does np.random.shuffle() do to a NumPy array?
easy
A. Randomly rearranges the elements of the array in-place
B. Sorts the array elements in ascending order
C. Creates a new shuffled copy of the array without changing the original
D. Reverses the order of elements in the array
Solution
Step 1: Understand the function purpose
np.random.shuffle() is designed to mix elements randomly within the array.
Step 2: Check how it modifies the array
This function changes the original array directly (in-place), not creating a new one.
Final Answer:
Randomly rearranges the elements of the array in-place -> Option A
Quick Check:
Shuffle = random in-place rearrangement [OK]
Hint: Shuffle mixes elements inside the same array [OK]
Common Mistakes:
Thinking shuffle returns a new array
Confusing shuffle with sorting
Assuming shuffle reverses elements
2. Which of the following is the correct syntax to shuffle a 1D NumPy array named arr?
easy
A. np.random.shuffle(arr, axis=1)
B. np.shuffle(arr)
C. arr.shuffle()
D. np.random.shuffle(arr)
Solution
Step 1: Identify the correct function call
The shuffle function is inside the np.random module, so it must be called as np.random.shuffle().
Step 2: Check the parameters
It takes the array as the only argument. The axis parameter is not valid for 1D arrays.