Mastering Python's random Module ๐ŸŽฒ

Dice icon

Mastering Python's random Module ๐ŸŽฒ

The random module provides versatile tools for generating random numbers, shuffling sequences, sampling, and more. It's widely used for testing, simulations, and probabilistic operations.

1. Generating Random Numbers: uniform, randint, random

import random

print(random.random())         # float between 0.0 and 1.0
print(random.uniform(10, 20))  # float between 10 and 20
print(random.randint(1, 6))    # integer between 1 and 6

2. Fixing the Seed for Reproducibility

import random

random.seed(123)
print([random.randint(1, 100) for _ in range(5)])  # same results every time

3. Shuffling and Sampling Lists

import random

arr = list(range(1, 11))
random.shuffle(arr)               # shuffle list randomly
print(arr)

sample = random.sample(arr, 3)    # select 3 unique elements
print(sample)

4. Weighted and Simple Random Choices

import random

choices = ['Rock', 'Paper', 'Scissors']
print(random.choice(choices))  # single random choice

weighted = random.choices(choices, weights=[1, 2, 1], k=5)
print(weighted)  # 'Paper' more likely chosen due to higher weight

Summary

  • Use random(), uniform(), randint() for varied random numbers.
  • Ensure reproducibility with seed().
  • shuffle() and sample() help randomize or extract from lists.
  • choice() and choices(weights) offer simple and weighted selection.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“