← Back to Articles
Tutorial

Understanding Python's choice() Function

Learn how to use Python's choice() function for selecting random elements from lists.

Paragraph 1: The choice() function in Python is a part of the random module and is used to select a random item from a non-empty sequence like a list or tuple.

Paragraph 2: To use the choice() function, you must first import the random module. The function is straightforward: pass a list, tuple, or string to random.choice() to get a random element. For example, random.choice(['apple', 'banana', 'cherry']) might return 'banana'.

Paragraph 3: Best practices include ensuring the sequence is not empty to avoid errors. It's also wise to use choice() when you need a simple random selection without replacement from a list.

Paragraph 4: Common mistakes include using choice() on an empty sequence, which raises an IndexError. Additionally, not importing the random module will result in a NameError.

Code Examples

Example 1

import random
fruits = ['apple', 'banana', 'cherry']
print(random.choice(fruits))

Example 2

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

More Python Tutorials