Course contentsShow
← Python
Lesson 693 of 1,06011. Standard Library EssentialsFree lesson

Selecting and Shuffling Sequences with random

Select elements with choice, shuffle lists in place, and use sample to draw without replacement while preserving the original sequence.

In this lesson, you will learn how to manipulate sequences by selecting random items and reordering elements using the random module.

When working with data sequences, you often need to pick a single item, randomize the order of a list, or draw a subset of elements. The random module provides three highly efficient tools for these tasks.

Selecting a Single Element

To pick one random element from a sequence, such as a list or a tuple, use random.choice(). This is useful for simulations or randomly assigning tasks.

import random

options = ["Python", "JavaScript", "Rust", "Go"]
selection = random.choice(options)
print(f"The randomly selected language is: {selection}")

Shuffling Sequences In-Place

If you need to change the order of elements within a list, use random.shuffle(). Note that this function modifies the list in-place and returns None. Because it rearranges the original list directly, it is memory-efficient for large sequences.

cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(f"Shuffled deck: {cards}")

Drawing Without Replacement

When you need to select multiple items from a sequence but want to ensure each item is unique (sampling without replacement), use random.sample(). Unlike shuffle, sample does not modify the original sequence; instead, it returns a brand-new list containing the selected elements.

items = ["apple", "banana", "cherry", "date", "elderberry"]
# Draw 3 unique items
subset = random.sample(items, 3)

print(f"Original list preserved: {items}")
print(f"Random subset: {subset}")

It is important to note that random.sample() will raise a ValueError if the sample size you request is larger than the sequence itself. By combining choice, shuffle, and sample, you can handle most requirements involving randomness in your Python programs without needing external libraries.

Key Takeaway: Use random.choice() for single items, random.shuffle() to randomize a list in-place, and random.sample() to extract a subset of unique items without altering your original data.