[Python] Randomly Sorting Lists: Using shuffle vs. sample

To randomly shuffle list elements in Python, there are two methods in the random module: the sample() function and the shuffle() function.

While both achieve the same result of “reordering,” they differ in behavior regarding whether they modify the original list. This article explains their characteristics and how to choose the right one for your needs.

目次

1. random.sample(): Creating a New List (Non-Destructive)

The random.sample() function creates a new list by randomly selecting a specified number of elements from a sequence.

By specifying the “total number of elements (length)” as the count to retrieve, you can obtain a new shuffled list while maintaining the original list intact.

Implementation Example: Shuffle Play for Music

In this scenario, we keep the original album track order but create a separate random playlist for playback.

import random

# List of album tracks
album_tracks = [
    "Track 01: Intro",
    "Track 02: Summer Breeze",
    "Track 03: Midnight Blue",
    "Track 04: The Finale"
]

# 1st argument: Target list
# 2nd argument: Number of elements (here, the length of the list)
# The original list is unchanged; a new shuffled list is returned
shuffled_playlist = random.sample(album_tracks, len(album_tracks))

print("--- Original Album ---")
print(album_tracks)

print("\n--- Shuffled Playlist ---")
print(shuffled_playlist)

Execution Result (Example)

--- Original Album ---
['Track 01: Intro', 'Track 02: Summer Breeze', 'Track 03: Midnight Blue', 'Track 04: The Finale']

--- Shuffled Playlist ---
['Track 03: Midnight Blue', 'Track 01: Intro', 'Track 04: The Finale', 'Track 02: Summer Breeze']

2. random.shuffle(): Updating the List Itself (Destructive)

The random.shuffle() function reorders the passed list in-place.

Since it does not create a new list, it is memory efficient, but the original order is lost. Note that the return value is None.

Implementation Example: Card Game Deck

In this scenario, we shuffle a deck of cards, completely changing their order.

import random

# Deck of cards (4 cards for simplicity)
deck = ["Ace of Spades", "King of Hearts", "Queen of Diamonds", "Jack of Clubs"]

print(f"Before shuffle: {deck}")

# Modifies the list itself (No return value, so do not assign to a variable)
random.shuffle(deck)

print(f"After shuffle : {deck}")

Execution Result (Example)

Before shuffle: ['Ace of Spades', 'King of Hearts', 'Queen of Diamonds', 'Jack of Clubs']
After shuffle : ['Queen of Diamonds', 'Ace of Spades', 'Jack of Clubs', 'King of Hearts']

Summary

FunctionSyntaxOriginal ListFeatures
samplerandom.sample(l, len(l))UnchangedUse when you want to keep original data. Returns a new list.
shufflerandom.shuffle(l)ModifiedUse to save memory or when the original order is not needed.

Google スプレッドシートにエクスポート

Choose between the non-destructive sample and the destructive shuffle according to your specific requirements.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次