How to shuffle a list in Python

In this Python tutorial, we will learn how to shuffle a list in Python. We will take a list with some elements in it. Our goal is to shuffle the elements in the list using Python.

To shuffle the elements in a list means to give random orders of the elements. So we can also say that in this tutorial we will learn how to change the orders of elements in a list randomly in Python.

Shuffle a list in Python

There are a lot of ways to shuffle the elements in a list in Python. But as this is CodeSpeedy we always go for the easiest way and efficient way to solve a problem. Thus here we will use the easiest way to shuffle elements in a list in Python.

The module will use:

random module

The random module will help us to shuffle a list.

Learn some more uses of this module from the below tutorials,

Shuffle the elements in a list in Python using random module

In the random module, we got method random.shuffle()

random.shuffle() can be used to shuffle object.

Pass the object whose elements you want to shuffle in the method.

import random
a_list =['545','yfsjh','69874','fayrug','3254','codespeedy']
random.shuffle(a_list)
print(a_list)

output:

$ python codespeedy.py
['3254', 'fayrug', 'codespeedy', '69874', 'yfsjh', '545']

Each time you will run this code, the list will be shuffled in a random order.

Now take another example

randomly arrange items in a list in python for multiple times

Using for loop we can shuffle the list for any number of times we want

import random
a_list =['545','yfsjh','69874','fayrug','3254','codespeedy']
for x in range(10):
    random.shuffle(a_list)
    print(a_list)

Output:

$ python codespeedy.py
['3254', 'yfsjh', '69874', 'codespeedy', 'fayrug', '545']
['69874', 'fayrug', 'yfsjh', '545', '3254', 'codespeedy']
['3254', 'codespeedy', '545', 'yfsjh', 'fayrug', '69874']
['69874', 'yfsjh', '3254', '545', 'codespeedy', 'fayrug']
['545', 'codespeedy', '3254', 'fayrug', 'yfsjh', '69874']
['codespeedy', 'yfsjh', '69874', '545', 'fayrug', '3254']
['fayrug', '3254', 'yfsjh', '69874', '545', 'codespeedy']
['69874', 'yfsjh', '545', '3254', 'codespeedy', 'fayrug']
['69874', '545', 'yfsjh', 'codespeedy', '3254', 'fayrug']
['codespeedy', '3254', '545', '69874', 'yfsjh', 'fayrug']

This way we can randomly arrange list elements in Python easily.

Build a Number Guessing Game in Python

Leave a Reply

Your email address will not be published. Required fields are marked *