Sling Academy
Home/Python/Python: 3 Ways to Select Random Elements from a List

Python: 3 Ways to Select Random Elements from a List

Last updated: June 06, 2023

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!

Next Article: Python: How to Remove Elements from a List (4 Approaches)

Previous Article: Ways to Combine Lists in Python

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs