Python random.choices() method (original) (raw)

Last Updated : 05 Dec, 2024

The **choices() method returns multiple random elements from the list with replacement. Unlike random.choice(), which selects a single item, random.choices() allows us to select multiple items making it particularly useful for tasks like sampling from a population or generating random data.

**Example:

Python `

import random

a = ["geeks", "for", "python"]

print(random.choices(a, weights = [10, 1, 1], k = 5))

`

Output

['geeks', 'geeks', 'geeks', 'geeks', 'geeks']

Explanation:

**Note: Every time output will be different as the system returns random elements.

Let's take a closer look at random.choices() method:

Table of Content

Syntax of random.choices()

random.choices(population, weights=None, cum_weights=None, k=1)

Parameters

**Example of random.choices() method:

Python `

import random

Example 1: Simple Random Selection

a = ['apple', 'banana', 'cherry', 'date'] res = random.choices(a, k=3) print(res)

Example 2: Random Selection with Weights

w = [10, 20, 5, 1] res = random.choices(a, weights=w, k=3) print(res)

Example 3: Random Selection with Cumulative Weights

cw = [10, 30, 35, 36] # Cumulative sum of weights res = random.choices(a, cum_weights=cw, k=3) print(res)

Example 4: Selecting Random Characters from a String

ch = "abcdefghijklmnopqrstuvwxyz" res = random.choices(ch, k=5) print(res)

`

Output

['cherry', 'apple', 'apple'] ['cherry', 'banana', 'banana'] ['cherry', 'cherry', 'banana'] ['c', 'd', 'm', 'z', 's']

**Explanation:

Practical Applications of random.choices() method:

It allows for sampling with replacement, meaning the same item can be selected multiple times. Common practical applications include: