Python random.choice() function


The random.choice() function in Python is part of the built-in random module and is used to select a random element from a non-empty sequence, such as a list, tuple, or string. This function is particularly useful when you want to randomly pick an item from a collection of items.

Syntax

import random random_element = random.choice(sequence)
  • Parameters:
    • sequence: A non-empty sequence (like a list, tuple, or string) from which to select an item.

Return Value

  • Returns a randomly selected element from the provided sequence.

Example Usage

  1. Basic Example with a List:

    import random fruits = ['apple', 'banana', 'cherry', 'date'] random_fruit = random.choice(fruits) print(random_fruit) # Example output: 'banana'
  2. Using with a String: You can use random.choice() with strings, treating the string as a sequence of characters:

    letters = 'abcdefg' random_letter = random.choice(letters) print(random_letter) # Example output: 'c'
  3. Selecting Random Elements from a Tuple:

    colors = ('red', 'green', 'blue', 'yellow') random_color = random.choice(colors) print(random_color) # Example output: 'green'
  4. Multiple Random Selections: If you need to select multiple random items (with replacement), you can use a loop:

    for _ in range(3): print(random.choice(fruits)) # Randomly select 3 fruits

    Example output might look like:

    cherry banana apple
  5. Seeding the Random Number Generator: You can use random.seed() to ensure reproducibility:

    random.seed(1) # Seed the random number generator print(random.choice(fruits)) # Output will be the same each time the seed is set

Summary

  • random.choice(sequence) is a simple and effective way to select a random element from a non-empty sequence.
  • It is commonly used in scenarios such as games, simulations, and random sampling.
  • If the sequence is empty, random.choice() will raise an IndexError, so it's a good practice to ensure that the sequence is not empty before calling this function.