Explain Codes LogoExplain Codes Logo

Shuffling a list of objects

python
shuffle
random
list
Alex KataevbyAlex Kataev·Dec 14, 2024
TLDR

To shuffle a list, embrace the random.shuffle() method from Python's random module:

from random import shuffle my_list = ['apple', 'banana', 'cherry'] shuffle(my_list) print(my_list) # e.g., ['cherry', 'banana', 'apple']

This shuffles my_list in place. Copy the list first if you need to keep the original order.

An in-depth look at random.shuffle()

In-place shuffling: A close-up

random.shuffle() breathes life into the list, dancing with the elements and placing them in a random order. It's an in-place operation, meaning the list is modified directly, and the function returns None.

Take note: Only mutable sequences are eligible dance partners

random.shuffle() prefers to tango with mutable sequences only, meaning lists are a perfect match but tuples or strings will step on its toes, resulting in a TypeError. So, always ensure your dance partner is mutable for a seamless performance.

More than just prim and proper: Shuffling custom objects

random.shuffle() isn't picky; it will happily shuffle a list of custom objects or complex data structures:

from random import shuffle class Fruit: def __init__(self, name): self.name = name def __repr__(self): return f'Fruit({self.name})' fruits = [Fruit('Apple'), Fruit('Banana'), Fruit('Cherry')] shuffle(fruits) print(fruits) # e.g., [Fruit('Cherry'), Fruit('Banana'), Fruit('Apple')] # Even fruits love a little cha-cha-cha!

Common faux pas: Printing the shuffle()

Don't directly print the result of shuffle() as it returns None, causing confusion:

# Incorrect usage print(shuffle(my_list)) # This will print 'None', play the song before you start dancing!

To witness the wonderful dance, shuffle the list first, and then print it.

A handy alternative: random.sample

If you want to keep the original list intact and make a shuffled copy, use random.sample(). It's like having an instant replay of the random.shuffle() dance, but in a new setup:

from random import sample original_list = ['apple', 'banana', 'cherry'] shuffled_list = sample(original_list, len(original_list)) print(shuffled_list) # e.g., ['cherry', 'apple', 'banana'] # It's like watching the dance on replay, but the dancers are in different spots!

When we speak science: numpy's shuffle

For the scientific maestros, numpy grants access to np.random.shuffle() to shuffle numpy arrays effortlessly:

import numpy as np arr = np.array([1, 2, 3, 4, 5]) np.random.shuffle(arr) print(arr) # e.g., [5 3 1 4 2] # Who said scientists don't know how to party?