Home > Backend Development > Python Tutorial > How Do I Shuffle a List of Objects in Python?

How Do I Shuffle a List of Objects in Python?

Patricia Arquette
Release: 2024-12-07 21:19:13
Original
830 people have browsed it

How Do I Shuffle a List of Objects in Python?

Shuffling a List of Objects in Python [Duplicate]

The challenge of shuffling a list of objects in Python can be addressed using the random.shuffle() function. This function operates directly on the list, modifying its order in place, but does not return anything.

Example:

import random

b = [object(), object()]

random.shuffle(b)

print(b)  # Output: [<object object at 0x7f166992a890>, <object object at 0x7f166992a9a0>]
Copy after login

In this scenario, the list b is shuffled, resulting in a new ordering of its elements.

Explanation:

random.shuffle() accepts a mutable object as its argument and modifies its order by randomly rearranging its elements. Since a list is a mutable object, random.shuffle() can change its order directly.

It's important to note that random.shuffle() does not return the shuffled list or any value. Instead, it modifies the original list in place, which is a common practice in Python when operating on mutable objects.

Additional Information:

In Python, the convention for functions that mutate objects is to return None. This allows for concise syntax and consistency in code style.

The above is the detailed content of How Do I Shuffle a List of Objects in Python?. 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