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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots