How to shuffle list in Python using random.shuffle() function?

Posted in

How to shuffle list in Python using random.shuffle() function?
vinaykhatri

Vinay Khatri
Last updated on December 22, 2024

    In this Python tutorial, we will discuss the different functions and methods provided by the Python modules to shuffle the items of a list. We will also see how we can use the same method to shuffle the characters and items of any other sequential object like string, tuple, and dictionary. In this tutorial, the methods or functions that we are going to cover are

    Function Description
    random.shuffle(list_name) It performs the in-place operation and shuffles the actual list.
    random.sample(list_name, len(list_name)) It also shuffles the list but does not perform the shuffling on the actual list. Instead, create a copy of the list, perform shuffling and return the new list.
    numpy.random.shuffle(array) It is a numpy method to shuffle multidimensional numpy array.

    Shuffle Python list with random.shuffle() function

    The Python inbuilt random module provides a method shuffle(x) , that can shuffle the items of a sequential object like a list. Using the shuffle() function we can perform the in-place shuffling on a list.

    Syntax

    import random
    
    random.shuffle(x[, random])

    The shuffle method can accept two argument values.

    1. x : It is the sequential object (list) that items or characters need to be shuffled.
    2. random : It is an optional argument representing the random() function of the random module. It is the same function random.random() that returns a random float number value between 0.1 to 1.0.

    Return Value

    The shuffle performs the in-place operation, makes the changes on the actual value and returns None .

    Steps to shuffle a list in Python

    Here are the basic steps to shuffling a list

    Step 1: Import the random module

    random is an inbuilt Python module; we can import it on our list using the import statement. import random

    step 2: Create a List

    Now we need to create a list. To create a list, we can either use the list() function or the square bracket nation [] . x = [1,2,3,4,5]

    step 3: shuffle the list using the random.shuffle() function

    Use the random.shuffle() function to shuffle the list x. random.shuffle(x) Do not reassign the return value of shuffle back to the list, because it returns None.

    Python shuffle() example

    Let's see an example of shuffling a list in Python.

    #import the random module
    import random
    
    #the list to shuffle
    x = [50, 59, 63, 65, 66, 70, 78, 79, 86, 97, 100]
    
    #shuffle the list using the shuffle function
    random.shuffle(x)
    
    #print the shuffled list
    print(x)
    #output [59, 79, 63, 100, 70, 78, 66, 86, 97, 50, 65]
    
    
    #shuffle the list again
    random.shuffle(x)
    print(x)
    #output [50, 63, 78, 65, 86, 59, 66, 79, 70, 100, 97]

    Example 2

    Suppose we have two lists representing the deck of cards. The first list represents the shape of the card, and the second list represents the number of cards. Now we need to write a script that shuffles both lists and picks the first 3 cards.

    import random
    
    #shape
    card_shape = ['SPADE','HEART','DIAMOND','CLUB']
    
    #number 1 to 13
    card_numbers = list(range(1, 14))
    
    #shuffle both the list
    random.shuffle(card_shape)
    random.shuffle(card_numbers)
    
    #print the first 3 random cards
    print("Your 3 cards are:")
    print(card_numbers[0], "of", card_shape[0])
    print(card_numbers[1], "of", card_shape[1])
    print(card_numbers[2], "of", card_shape[2])
    

    Output

    Your 3 cards are:
    2 of CLUB
    3 of DIAMOND
    10 of SPADE

    Not in Place shuffling with Python shuffle() function

    The shuffle() function, shuffles the list of items in place. And if we do not want to perform the shuffling on the actual list, we have to create a copy of the list and then apply the shuffle method on the copied list. To create a copy of the list, we can use the copy() method. The copy method creates a shallow copy of the list and returns a new list.

    Example

    #import the random module
    import random
    
    #the list to shuffle
    x = [50, 59, 63, 65, 66, 70, 78, 79, 86, 97, 100]
    
    #copy the list
    copied_list = x.copy()
    
    #shuffle the copied list
    random.shuffle(copied_list)
    
    #print the actuale list
    print("The actual list (x) is: ", x)
    
    #print the copied shuffled list
    print("The shuffled list is: ", copied_list)

    Output

    The actual list (x) is: [50, 59, 63, 65, 66, 70, 78, 79, 86, 97, 100]
    The shuffled list is: [86, 50, 66, 79, 59, 65, 97, 100, 63, 78, 70]

    Note: Do not use the assignment operator = to copy the list e.g. copied_list = x . It will not copy the list. Instead, it will create a new list name copied_list that will also be pointing to the same list object as x .

    No inplace list shuffling with random.sample() function.

    In the above example, we see how we can create a copy of a list and shuffle using the shuffle() function, so it does not affect the actual list. The random method also provides a sample(x, k) method, which can return the k a number of randomly picked items from the sequential object x. We can use the sample() method to shuffle a list object when we do not want to perform the in-place shuffling.

    Syntax

    import random
    
    random.sample(population, k)

    The sample() method has two mandatory arguments. population : It is a sequential object like a list, tuple, string, set, and dictionary. that we want to shuffle. k : Define the number of elements that we want to choose from the population sequence.

    Return value

    It returns a list of k random items from the population object.

    Example

    Let's shuffle a list using the sample() function. When we want to shuffle a list with the sample() function, the value of k must be equal to the length of the list.

    #import the random module
    import random
    
    #the list to shuffle
    x = [50, 59, 63, 65, 66, 70, 78, 79, 86, 97, 100]
    
    #shuffled list
    shuffled = random.sample(x, k =len(x))
    
    #print the actual list
    print("The actual list (x) is: ", x)
    
    #print the copied shuffled list
    print("The shuffled list is: ", shuffled)
    

    How to shuffle a Numpy Multidimensional Array?

    With the help of the random.shuffle() and random.sample() methods, we can only shuffle a one-dimensional numpy array. Note: With sample(), we first need to change the numpy array to a list using the list function. Then only we can shuffle it with sample() function.

    Example

    import numpy as np
    import random
    
    #numpy 1d array
    array1= np.array([1,2,3,4,5])
    
    array2 = np.array([101,102,103,104])
    
    
    #shuffle array1 with shuffle
    random.shuffle(array1)
    
    print(array1)
    #output [1 3 4 5 2]
    
    #shuffle array2 with sample
    print(random.sample(list(array2), k= len(array2)))
    #output [104, 102, 103, 101]

    But when we deal with a multi-dimensional NumPy array there, we can not simply use these shuffle() or sample() functions to shuffle the items of the array. To shuffle a multi-dimensional numpy array, we can use the np.random.shuffle() function. The numpy module comes with its own random class and multiple methods that are inherited from the random modules and compatible with numpy arrays.

    Example

    Let's create a multi-dimensional numpy array and shuffle its items using the numpy.random.shuffle() .

    import numpy as np
    
    #multi dimensional array
    multi_d_array  = np.array(
            [[1,2],[3,4], [5,6], [8,9]], np.int32)
    
    print("Multi-D Array before Shuffling")
    print(multi_d_array)
    
    #shuffle the array
    np.random.shuffle(multi_d_array)
    
    print("\nMulti-D Array After Shuffling")
    print(multi_d_array)
    

    Output

    Multi-D Array before Shuffling
    [[1 2]
     [3 4]
     [5 6]
     [8 9]]
    
    Multi-D Array After Shuffling
    [[3 4]
     [5 6]
     [1 2]
     [8 9]]

    How to get the same result with each shuffle()

    The shuffle method uses the random function to shuffle the sequence items. The random method also provides the seed() method, which can modify the start point when a computer generates a random value. Generally, the random number generator uses the random seed(the start point when a computer generates a random number).

    With the help of random.seed() method, we can modify the seed value, and make it constant so every time, the random method generates the same random value and shuffle the same result.

    Example

    Let's write a script that shuffles the list with the shuffle() function but shows the same result.

    import random
    
    import random
    
    #list
    x = [20, 30, 40, 50, 60]
    
    #shuffle the 10 times
    for i in range(10):
        #seed the starting random points
        random.seed(20)
    
        #shuffle the list
        random.shuffle(x)
    
        print(f"Shuffled list {i+1}", x)
    

    Output

    Shuffled list 1 [60, 20, 50, 40, 30]
    Shuffled list 2 [30, 60, 40, 50, 20]
    Shuffled list 3 [20, 30, 50, 40, 60]
    Shuffled list 4 [60, 20, 40, 50, 30]
    Shuffled list 5 [30, 60, 50, 40, 20]
    Shuffled list 6 [20, 30, 40, 50, 60]
    Shuffled list 7 [60, 20, 50, 40, 30]
    Shuffled list 8 [30, 60, 40, 50, 20]
    Shuffled list 9 [20, 30, 50, 40, 60]
    Shuffled list 10 [60, 20, 40, 50, 30]

    In the output, you can see that even after a constant seed value, the output result of every shuffling is not the same. This is because the shuffle method performs the in-place operation, and with every shuffling, the list items' position changes in place, and the shuffle function performs a new operation on a brand new list.

    Still, you can see that because of the seed(20) there are many common shuffle values. We can see the full potential of the seed function with the sample() function. The sample() function does not change the actual list, which means with a constant seed, if we try to get a shuffle list with the sample function, we will get the same shuffled list every time.

    Example

    import random
    
    #list
    x = [20, 30, 40, 50, 60]
    
    #shuffle the 10 times
    for i in range(10):
        #seed the starting random points
        random.seed(20)
    
        #shuffle the list
        print(f"Shuffled list {i+1}", random.sample(x, k=len(x)))
    

    Output

    Shuffled list 1 [30, 40, 50, 20, 60]
    Shuffled list 2 [30, 40, 50, 20, 60]
    Shuffled list 3 [30, 40, 50, 20, 60]
    Shuffled list 4 [30, 40, 50, 20, 60]
    Shuffled list 5 [30, 40, 50, 20, 60]
    Shuffled list 6 [30, 40, 50, 20, 60]
    Shuffled list 7 [30, 40, 50, 20, 60]
    Shuffled list 8 [30, 40, 50, 20, 60]
    Shuffled list 9 [30, 40, 50, 20, 60]
    Shuffled list 10 [30, 40, 50, 20, 60]

    How Shuffle a String in Python?

    The random.shuffle() method cannot shuffle a string value. And if we try to shuffle a string object using shuffle() function we receive the TypeError: 'str' object does not support item assignment Error. This makes sense, the shuffle performs the in-place operation, and the string is an immutable data structure, and when we try to shuffle it in-place with the shuffle() function, we receive the error.

    Example

    import random
    
    string = "TechGeekBuzz"
    
    random.shuffle(string)
    
    print(string) 
    #Error TypeError: 'str' object does not support item assignment
    

    In order to shuffle a string, we can either use the sample() function or convert the string into a list, shuffle it with the shuffle function, and convert the list back to the string.

    Example 1 Shuffle the string by converting it into the list

    import random
    
    #string
    string = "TechGeekBuzz Hello"
    
    #convert the string into list
    letters = list(string)
    
    #shuffle the list
    random.shuffle(letters)
    
    #convert the shuffled letters back to string to create a shuffled string
    string = "".join(letters)
    
    print(string)
    

    Output

    zzeoeulecBeGhTkl H
    

    Example 2 Shuffle a string with the sample function

    import random
    
    #string
    string = "TechGeekBuzz Hello"
    
    #shuffle the string
    letters = random.sample(string, k=len(string))
    
    #convert the shuffled letters back to string to create a shuffled string
    string = "".join(letters)
    
    print(string)
    

    Output

    zuHeoe ThkclBlzGee
    
    

    How Shuffle a Dictionary in Python?

    The shuffle method can only work on a dictionary object if all the keys of the dictionary are integer values.

    Example

    import random
    
    #dictionary
    #{0: 100, 1: 101, 2: 102, 3: 103, 4: 104, 5: 105, 6: 106, 7: 107, 8: 108, 9: 109}
    a= dict(zip(range(10), range(100, 110)))
    
    print("Dictionary before shuffling")
    print(a)
    
    #shuffle the dictionary a
    random.shuffle(a)
    
    print("Dictionary after shuffling")
    print(a)

    Output

    Dictionary before shuffling
    {0: 100, 1: 101, 2: 102, 3: 103, 4: 104, 5: 105, 6: 106, 7: 107, 8: 108, 9: 109}
    Dictionary after shuffling
    {0: 103, 1: 108, 2: 104, 3: 107, 4: 101, 5: 106, 6: 109, 7: 105, 8: 100, 9: 102}
    

    And if any of the dictionary keys is a string or of any other data type, the shuffle method will throw the KeyError. To shuffle a dictionary with different data type keys, we first need to change the dictionary into a list of (key, value) tuple pairs, shuffle it and convert it back into a dictionary using the dict() function.

    import random
    
    #dictionary
    #{0: 100, 1: 101, 2: 102, 3: 103, 4: 104, 5: 105, 6: 106, 7: 107, 8: 108, 9: 109}
    a= dict(zip(range(10), range(100, 110)))
    
    print("Dictionary before shuffling")
    print(a)
    
    #list of (key,value) tuples
    a = list(a.items())
    
    #shuffle the list
    random.shuffle(a)
    
    #convert the list into dictionary
    a = dict(a)
    
    print("Dictionary after shuffling")
    print(a)
    

    Output

    Dictionary before shuffling
    {0: 100, 1: 101, 2: 102, 3: 103, 4: 104, 5: 105, 6: 106, 7: 107, 8: 108, 9: 109}
    Dictionary after shuffling
    {0: 100, 3: 103, 6: 106, 8: 108, 4: 104, 1: 101, 2: 102, 9: 109, 5: 105, 7: 107}

    Conclusion

    The random module has two methods to shuffle a list in Python, shuffle(), and sample(). The shuffle() method accepts the list object as an argument, shuffles it in place, and returns None. The sample() method can also shuffle a list object, but it picks the k number of random items from a sequential object and returns it as a list. To shuffle a numpy multi-dimensional array, the numpy module itself comes a random class with the shuffle() method to shuffle the array.

    People are also reading:

    Leave a Comment on this Post

    0 Comments