How to Shuffle a List in Python Without using the Shuffle() Function

In the world of programming, there are often multiple ways to achieve a single goal. This is true in Python, where you may want to shuffle a list of items.

The Python language offers the shuffle() function to do this, but what if you need to shuffle a list without using this function? This tutorial shows you two alternative methods to shuffle a list in Python without making use of the shuffle() function.

Method 1: Using the Random Module and sample() Function

Python’s random module provides the sample() function, which can be used to shuffle a list without employing the shuffle() function.

The sample() function takes two parameters – the list you want to shuffle and the number of items you want from the list. If you want the entire shuffled list, the number of items should be the length of the list.

[3, 1, 2, 5, 4]

Method 2: Using Random Module and randint() Function

The second method uses the randint() function, also from the random module. The randint() function generates a random integer, which can be used to randomly select and remove items from the original list to a new list, thereby shuffling the list.

[1, 5, 4, 2, 3]

Displaying the Full Code

Conclusion

It’s possible to shuffle a list in Python without resorting to the shuffle() function. The sample() and randint() functions from Python’s random module serve as feasible alternatives to shuffle(). Either method can serve as a flexible and powerful tool for randomizing your list data when necessary.