Home >Backend Development >Python Tutorial >Why Does Python's `random.shuffle()` Return `None` and How Can I Use It Correctly?

Why Does Python's `random.shuffle()` Return `None` and How Can I Use It Correctly?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 00:19:11598browse

Why Does Python's `random.shuffle()` Return `None` and How Can I Use It Correctly?

Shuffling a List of Objects

Problem:

Mistakes can occur when attempting to shuffle a list of objects using the random.shuffle() function. The expected shuffling behavior doesn't seem to occur, and the function outputs None instead.

Solution:

To effectively shuffle a list of objects, use the shuffle() function from the random module as follows:

from random import shuffle

objects = [obj1, obj2, obj3]  # initialize the list of objects
shuffle(objects)  # shuffle the objects in place

Explanation:

Unlike some other programming languages, in Python, random.shuffle() operates in place, meaning it modifies the original list without returning a new one. Additionally, it's common practice for functions in Python to return None when mutating objects is intended.

Sample Code:

from random import shuffle

x = [[i] for i in range(10)]
shuffle(x)
print(x)

This will shuffle the list of lists x and print the shuffled result.

Note:

It's important to remember that shuffle() alters the original list, so subsequent operations or accesses to the list will reflect the changes made by shuffle().

The above is the detailed content of Why Does Python's `random.shuffle()` Return `None` and How Can I Use It Correctly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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