Python random() function


The random module in Python is a built-in library that provides functions to generate random numbers and perform random operations. It is widely used for tasks such as simulation, random sampling, and shuffling data. The random numbers generated can be used in games, testing, and modeling applications.

Key Functions in the random Module

Here are some of the commonly used functions in the random module:

  1. random.random()

    • Returns a random float in the range [0.0,1.0)[0.0, 1.0).
    import random random_float = random.random() print(random_float) # Example output: 0.37444887175646646
  2. random.randint(a, b)

    • Returns a random integer NN such that a≤N≤ba \leq N \leq b.
    random_int = random.randint(1, 10) print(random_int) # Example output: 7
  3. random.choice(sequence)

    • Returns a random element from a non-empty sequence (like a list or string).
    items = ['apple', 'banana', 'cherry'] random_item = random.choice(items) print(random_item) # Example output: 'banana'
  4. random.shuffle(sequence)

    • Shuffles the elements of a mutable sequence (like a list) in place.
    deck = [1, 2, 3, 4, 5] random.shuffle(deck) print(deck) # Example output: [3, 1, 4, 5, 2]
  5. random.sample(population, k)

    • Returns a list of kk unique elements chosen from the population sequence, without replacement.
    population = [1, 2, 3, 4, 5] sample = random.sample(population, 3) print(sample) # Example output: [4, 1, 3]
  6. random.uniform(a, b)

    • Returns a random float NN such that a≤N≤ba \leq N \leq b.
    random_float_range = random.uniform(1.0, 10.0) print(random_float_range) # Example output: 5.780224046152803
  7. random.seed(a=None)

    • Initializes the random number generator. If you want reproducible results, you can use a specific seed value.
    random.seed(1) print(random.random()) # Output: 0.13436424411240122

Example Usage

Here’s an example that combines several of the functions above:

import random # Set the seed for reproducibility random.seed(42) # Generate a random float print("Random float:", random.random()) # Generate a random integer print("Random integer:", random.randint(1, 100)) # Choose a random item from a list fruits = ['apple', 'banana', 'cherry', 'date'] print("Random fruit:", random.choice(fruits)) # Shuffle a list cards = ['Ace', 'King', 'Queen', 'Jack'] random.shuffle(cards) print("Shuffled cards:", cards) # Get a sample of unique items numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("Random sample:", random.sample(numbers, 3))

Summary

  • The random module provides a wide variety of functions for generating random numbers and performing random operations.
  • It is useful in simulations, testing, and games.
  • By setting the seed, you can make random operations reproducible, which is often useful for debugging or testing purposes.