Home > Backend Development > Python Tutorial > Why Does Python's `random.shuffle` Return `None` When Shuffling Objects?

Why Does Python's `random.shuffle` Return `None` When Shuffling Objects?

Susan Sarandon
Release: 2024-12-14 14:36:20
Original
609 people have browsed it

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)
Copy after login

Output:

[[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template