Shuffling a list of objects
To shuffle a list, embrace the random.shuffle()
method from Python's random
module:
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:
Common faux pas: Printing the shuffle()
Don't directly print the result of shuffle()
as it returns None, causing confusion:
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:
When we speak science: numpy's shuffle
For the scientific maestros, numpy grants access to np.random.shuffle()
to shuffle numpy arrays effortlessly:
Was this article helpful?