Open In App

How to Choose Elements from the List with Different Probability using NumPy

Last Updated : 27 Sep, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

In NumPy, numpy.random.choice() function allows us to randomly pick elements from a list. Unlike normal random selection, this method lets us assign different probabilities to each element, so some items are more likely to be chosen than others.

Here we select one element uniformly at random (equal probability for each item).

Python
import numpy as np
arr = [1, 2, 3, 4]
num = np.random.choice(arr)
print(num)

Output
4

Explanation: Since no probabilities are specified, each element in the list has the same chance of being selected.

Syntax

numpy.random.choice(a, size=None, replace=True, p=None)

Parameters:

  • a: 1D array-like -> Input list or array to sample from.
  • size: int or tuple, optional -> Number of samples to draw.
  • replace: bool, optional -> If True (default), same element can be selected multiple times. If False, elements are chosen without replacement.
  • p: 1D array-like, optional -> Probabilities associated with each element. Must sum to 1.

Return Value: Returns a NumPy array containing the randomly chosen elements.

Examples

Example 1: In this example, we randomly select one element from the list with equal probability.

Python
import numpy as np
lst = [10, 20, 30, 40, 50]
num = np.random.choice(lst)
print("Selected:", num)

Output
Selected: 20

Explanation: Here, every element has the same chance of being selected since no probability distribution is provided.

Example 2: In this example, we select the element 40 every time by assigning 100% probability to it.

Python
import numpy as np
lst = [10, 20, 30, 40, 50]
res = np.random.choice(lst, 3, p=[0, 0, 0, 1, 0])
print("Selected list:", res)

Output
Selected list: [40 40 40]

Explanation: The probability is set to 1 for element 40 and 0 for all others, so only 40 is selected repeatedly.

Example 3: Here we select elements 30 and 40 randomly with equal probability using the p parameter.

Python
import numpy as np
lst = [10, 20, 30, 40, 50]
res = np.random.choice(lst, 3, p=[0, 0, 0.5, 0.5, 0])
print("Selected list:", res)

Output
Selected list: [30 30 40]

Explanation: Only 30 and 40 are possible outcomes. Since both have equal probability (0.5 each), they appear randomly in the output.


Explore