← Back to Articles
Tutorial

Pick Random Element from List in Python

Learn how to select a random element from a list in Python with examples and best practices.

Working with lists in Python is a common task, and often you might need to select a random element from a list. This process is straightforward thanks to Python's built-in libraries.

To pick a random element from a list in Python, you can use the 'random' module, which provides a variety of functions for random number generation and selection. The 'random.choice()' function is particularly useful as it selects a random item from a list. For example, if you have a list of colors and want to choose one at random, 'random.choice()' simplifies the task.

When using 'random.choice()', it's important to ensure your list is not empty, as this will cause an error. Additionally, consider using 'random.choices()' if you need to select multiple elements or want to specify weights for selection probabilities.

A common mistake is not importing the 'random' module before trying to use 'random.choice()'. Another error is attempting to use 'random.choice()' on an empty list, which will result in an 'IndexError'. Always validate your list before performing operations on it.

Code Examples

Example 1

import random
my_list = [1, 2, 3, 4, 5]
random_element = random.choice(my_list)
print(random_element)

Example 2

import random
colors = ['red', 'blue', 'green', 'yellow']
random_color = random.choice(colors)
print(random_color)

More Python Tutorials