How to randomly select elements of an array with NumPy in Python ?
Last Updated :
23 Jul, 2025
Randomly selecting elements from an array means choosing random elements from the array. NumPy offers several efficient methods to pick elements either with or without repetition. For example, if you have an array [1, 2, 3, 4, 5] and want to randomly select 3 unique elements, the output might look like [1 5 2]. Let’s explore different methods to do this efficiently.
Using numpy.random.choice()
This method randomly selects elements from an array without repetition. It’s useful when you need unique random samples of a given size.
Python
import numpy as np
a= np.array([1, 2, 3, 4, 5])
res = np.random.choice(a, size=3, replace=False)
print(res)
Explanation: np.random.choice(a, size=3, replace=False)selects 3 unique random elements from the array a, where size=3 means 3 values are chosen, and replace=Falseensures no repetition.
Using numpy.random.shuffle()
This shuffles the array in-place, meaning the original array is modified. It's very fast and memory-efficient; just take the first n values after shuffle.
Python
import numpy as np
a= np.array([1, 2, 3, 4, 5])
np.random.shuffle(a)
res = a[:3]
print(res)
Explanation: np.random.shuffle(a) randomly shuffles the elements of array a in-place, changing the original order. res = a[:3] then selects the first 3 elements from the shuffled array.
Using numpy.random.permutation()
This method returns a new shuffled copy of the original array. The original array remains unchanged, making it safer for reuse.
Python
import numpy as np
a= np.array([1, 2, 3, 4, 5])
b = np.random.permutation(a)
res = b[:3]
print(res)
Explanation: np.random.permutation(a) returns a shuffled copy of array a without modifying the original. res = b[:3] selects the first 3 elements from this shuffled copy.
Using replace=True
This allows sampling with repetition, so the same value can appear multiple times. It’s useful when you need more samples than unique elements.
Python
import numpy as np
a= np.array([1, 2, 3, 4, 5])
res = np.random.choice(a, size=3, replace=True)
print(res)
Explanation: np.random.choice(a, size=3, replace=True) randomly selects 3 elements from array a, allowing repetition. This means the same element can appear multiple times in the result.
Related articles
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice