How does the random.choice() function work in Python?

QuestionsQuestions8 SkillsProRun a Small ProgramAug, 29 2025
0249

The random.choice() function in Python is used to select a random element from a non-empty sequence, such as a list, tuple, or string. It returns one randomly selected item from the provided sequence.

Syntax

random.choice(sequence)

Parameters

  • sequence: This is the non-empty sequence from which you want to select a random element.

Example

Here’s a simple example demonstrating how to use random.choice():

import random

# A list of fruits
fruits = ['apple', 'banana', 'cherry', 'date']

# Select a random fruit
random_fruit = random.choice(fruits)

print(f"The randomly selected fruit is: {random_fruit}")

In this example, random.choice(fruits) will return one of the fruits from the list fruits at random each time the code is executed.

0 Comments

no data
Be the first to share your comment!