Selecting a Random Item from a List

Write a Python program that uses the random module to select a random item from a list.

Example 1:

Input: [1, 2, 3, 4, 5]
Output: 3  # Output may vary

Example 2:

Input: ['apple', 'banana', 'cherry']
Output: 'banana'  # Output may vary

The random module contains a function choice() that selects a random item from a list.

import random

# Define the function
def select_random_item(lst):
    return random.choice(lst)

# Test the function
print(select_random_item([1, 2, 3, 4, 5]))  # Output may vary
print(select_random_item(['apple', 'banana', 'cherry']))  # Output may vary

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!