Generating Random Numbers and Selecting Random Elements in Python

The random module provides functions to pseudo-random number generation and operations on sequences. All examples assume import random has been executed.

Floating-Point Generation

random.random() produces a float in the half-open interval [0.0, 1.0).

value = random.random()   # e.g., 0.375924617213

random.uniform(low, high) returns a float n such that if low <= high, then low <= n <= high; if the arguments are reversed, high <= n <= low. The endpoints may or may not be included depending on floating-point rounding.

x = random.uniform(5, 10)   # somewhere between 5 and 10
y = random.uniform(10, 5)   # also between 5 and 10

Integer Generation

random.randint(begin, end) returns an integer i with begin <= i <= end. The lower bound must not exceed the upper bound.

dice_roll = random.randint(1, 6)

random.randrange(start, stop, step) works like range(start, stop, step) but returns a single randomly chosen element from that arithmetic progression. step defaults to 1, and start defaults to 0. The stop value is exclusive.

even = random.randrange(2, 20, 2)    # randomly selects from [2,4,6,...,18]

Selection From a Sequence

random.choice(seq) picks a single element uniformly from a non-empty sequence such as a list, tuple, or string.

fruit = random.choice(["apple", "banana", "cherry"])
letter = random.choice("hello")

random.sample(population, k) returns a new list containing k unique elements chosen from the population without replacement. The original collection remains unchanged.

pool = list(range(1, 21))
picked = random.sample(pool, 4)   # e.g., [3, 17, 7, 11]

Shuffling a List In-Place

random.shuffle(lst) rearranges the items of a list randomly. It modifies the list directly and returns None.

cards = ["A", "K", "Q", "J", "10"]
random.shuffle(cards)

Tags: python Random standard library Code Examples

Posted on Thu, 04 Jun 2026 18:55:45 +0000 by Backara_Drift