Home >Backend Development >Python Tutorial >Why Does Python's `random.shuffle` Return `None` When Shuffling Objects?
Shuffling a List of Objects
When attempting to shuffle a list of objects using the random.shuffle function in Python, you may encounter the issue of receiving a None output. Unlike lists of integers, shuffling objects requires a bit more consideration.
Understanding random.shuffle
random.shuffle operates on mutable objects in place, meaning it directly modifies the original list. This function does not return the shuffled list but rather modifies the input list. As a result, it returns None to indicate that no actual value is being returned.
Solution
To resolve the issue, ensure that the input list contains mutable objects, such as lists. Here's an example:
from random import shuffle # Create a list of lists as objects x = [[i] for i in range(10)] # Shuffle the list of objects in place shuffle(x) # Print the shuffled list print(x)
Output:
[[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
By using lists as objects, random.shuffle can effectively modify the original list and provide the desired shuffled output. Remember that when dealing with mutable objects, it's common for functions to return None after modifying the objects in place.
The above is the detailed content of Why Does Python's `random.shuffle` Return `None` When Shuffling Objects?. For more information, please follow other related articles on the PHP Chinese website!