Python: 3 Ways to Select Random Elements from a List

Updated: June 6, 2023 By: Khue Post a comment

This succinct and practical article shows you a couple of different ways to randomly select one or multiple elements from a given list in Python. Without any further ado, let’s get started.

Using random.choices() and random.choice()

random.choices() is a function in the random module that returns a list of k random elements from a population with replacement (i.e., the same element can be selected more than once). If k is not specified, it defaults to 1.

Example:

import random 

# Set the seed to 0 so that the results are the same each time
random.seed(0)

colors = ['red', 'green', 'blue', 'yellow', 'orange', 'purple', 'brown']

random_colors = random.choices(colors, k=3)
print(random_colors)

Output:

['purple', 'purple', 'blue']

You can also use the weights parameter to increase the likelihood of an element appearing in the results.

Example:

import random 

colors = ['red', 'green', 'blue', 'yellow', 'orange', 'purple', 'brown']

# Set weights for each color
weights = [100, 50, 1, 1, 1, 1, 1]
random_colors = random.choices(colors, weights=weights, k=3)
print(random_colors)

The probability of red and green appearing in the result is much higher than the other colors. Run the code above multiple times and see the results.

In case you only need to get a single random element from a list, you can use the random.choice() function:

import random 

random.seed(1)

colors = ['red', 'green', 'blue', 'yellow', 'orange', 'purple', 'brown']

random_color = random.choice(colors)
print(random_color)

Output:

green

Using random.shuffle() and list slicing

If you want to randomly extract N unique elements from a list, you can do the following:

  1. Shuffle the list using the random.shuffle() function
  2. Get the first N elements from the shuffled list using the list-slicing syntax

Example:

import random 

random.seed(0)

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

random.shuffle(list)
random_items = list[:4]
print(random_items)

Output:

[8, 9, 2, 6]

Using random.sample()

The random.sample() function can be used to choose k unique random elements from a population sequence.

Example:

import random 

random.seed(0)

words = ['apple', 'banana', 'cherry', 'slingacademy.com']

random_words = random.sample(words, 2)
print(random_words)

Output:

['slingacademy.com', 'banana']

That’s it. Happy coding!