Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Python randomshuffle function to shuffle list
    python

    Python randomshuffle function to shuffle list

    March 30, 2023No Comments11 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Python’s random.shuffle() method for randomized list generation

    This tutorial will teach you how to use Python’s random.shuffle() method to randomly shuffle a list. Discover how to randomly mix up a string, dictionary, or Python sequence.

    When we say to shuffle a list, we intend to rearrange the entries in the list. Mix up a deck of cards, for instance.

    The following methods of a random module to randomly choose items from a list are covered:

    Python.

    Python provides

    Function Description

    random.shuffle(list1)
    Shuffle

    list

    in-place (preferred way)

    random.sample(seq, len(seq))
    Shuffle list not in place to return a new shuffled list. (non-preferred way) OR

    To shuffle an immutable sequence such as

    string

    or range.

    np.random.shuffle(array)
    Shuffling multidimensional array

    methods for shuffling lists.

    Table of contents


    • The random.shuffle() function

    • Shuffle a List

    • Randomly Shuffle Not in Place


      • Option 1: Make a Copy of the Original List

      • Option 2: Shuffle list not in Place using random.sample()

    • Shuffle Two Lists At Once With Same Order

    • Shuffling NumPy Multidimensional Array

    • Shuffle a List to Get the Same Result Every time

    • Shuffle a String


      • Shuffle a String by Converting it to a List

      • Approach Two: Shuffling a String, not in place

    • Shuffle Range of Integers

    • Shuffle a Dictionary in Python

    • Shuffle a Python generator

    • Next Steps

    Syntax:

    The

    random.shuffle(x, random)

    Run

    It means to randomly reorder the elements of a sequence x. Parameters:

    There are two inputs for the random.shuffle() method. Just one of these two options is required.

    parameter.

    Value Returned


    • x

      : It is a sequence you want to shuffle such as list.

    • random

      : The optional argument random is a function returning a random float number between 0.1 to 1.0. This function decides how to shuffle a sequence. If not specified, by default Python uses the

      random.random()

      function.


      Note

      : this

      parameter deprecated

      since version 3.9, will be removed in version 3.11

    This function returns None and shuffles the sequence in situ. With this method, you may rearrange the elements in a changeable

    sequence.

    Shuffle a List

    These are the procedures to randomly reorder a list in

    Python


    1. Create a list

      Create a

      list

      using a

      list()

      constructor. For example,

      list1 = list([10, 20, 'a', 'b'])


    2. Import random module

      Use a

      random module

      to perform the random generations on a list


    3. Use the shuffle() function of a random module

      Use the

      random.shuffle(list1)

      function to shuffle a

      list1

      in place.

      the


      shuffle()

      shuffles the original list

      , i.e., it changes the order of items in the original list randomly and doesn’t return a new list


    4. Display the shuffled list

      As

      shuffle()

      function doesn’t return anything. Use

      print(list1)

      to display the original/resultant list.


    5. Get shuffled list instead of modifying the original list

      Use the

      random.sample()

      function to

      shuffle the list not in place

      to get the new shuffled list in return instead of changing the original list.

      OR

      Make a copy of the original list before shuffling (Ideal way)


    6. Customize the shuffling if needed

      If you want to perform shuffling as per your need, you can pass a custom function in the place of the

      random

      argument, which will dictate the

      shuffle()

      function on how to randomize a list’s items.

    Illustration

    –

    import random
    number_list = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
    # Original list
    print(number_list)
    # Output [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
    # List after first shuffle
    random.shuffle(number_list)
    print(number_list)
    # Output [42, 28, 14, 21, 7, 35, 49, 63, 56, 70]
    # List after second shuffle
    random.shuffle(number_list)
    print(number_list)
    # Output [14, 21, 70, 28, 49, 35, 56, 7, 42, 63]
    

    A look at the output reveals that the list elements’ locations are

    changed.

    Randomly Shuffle Not in Place

    The shuffle() function, as you may know, reorders the original list’s elements arbitrarily in place and returns Nothing. Nonetheless, the original order or list is required the vast majority of the time.

    The original list may be preserved in two ways. These selections do not alter the source list but rather return a new, randomly

    list.

    Before rearranging the original list, make a duplicate.

    )

    import random
    numbers = [33, 66, 99, 188, 256, 412, 748]
    # copy to new list
    new_list = numbers.copy()
    # shuffle the new list
    random.shuffle(new_list)
    print("Original list : ", numbers)
    #  [33, 66, 99, 188, 256, 412, 748]
    print("List after shuffle", new_list)
    # Output [188, 412, 33, 256, 66, 748, 99]
    

    Run

    Option 2: Shuffle list not in Place using

    If you want a different list without altering the original one, use the random.sample() method.

    If you supply a sample size into the random.sample() method, it will return that many items from the random list. To retrieve three randomly selected elements from a list, for instance, use sample(myList, 3).

    If we provide a sample size equal to the size of the original list, we’ll get back the reshuffled version of that list.

    I’ll give you an example. Here I am randomly reordering the Employee

    objects.

    import random
    # custom class
    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
    emp1 = Employee("Kelly", 10000)
    emp2 = Employee("Abigail", 8000)
    emp3 = Employee("Sampson", 12000)
    emp4 = Employee("Joe", 7000)
    # list with 4 objects
    emp_list = [emp1, emp2, emp3, emp4]
    # print original list
    for emp in emp_list:
        print(emp.name, emp.salary, end=', ')
    # Output Kelly 10000, Abigail 8000, Sampson 12000, Joe 7000,
    # shuffle list of objects
    # sample size (k) = length of a list
    shuffledList = random.sample(emp_list, k=len(emp_list))
    print("\nPrinting new shuffled list of employee object")
    for emp in shuffledList:
        print(emp.name, emp.salary, end=', ')
    # Output Joe 7000, Kelly 10000, Abigail 8000, Sampson 12000,
    

    Run

    For small values of len(x), the total number of permutations of x may soon grow to be larger than the period of most random number generators, as stated in the official Python documentation. This means that it is impossible to construct the vast majority of possible permutations of a lengthy sequence. The longest sequence that may be generated using the Mersenne Twister random number generator, for instance, is 2080 numbers long. Hence, put it to good use right now.

    approach.

    Shuffle Two Lists At Once With Same Order

    If you wish the shuffle order of two lists to remain the same, you may use the Shuffle command. Take, for instance, a pair of lists, one containing employee names and the other a pay. Let’s have a look at how to randomize multiple lists while yet preserving their

    order.

    import random
    # list of names
    employees = ['Jon', 'Emma', 'Kelly', 'Jason']
    # list of numbers
    salary = [7000, 6500, 9000, 10000]
    # Lists before Shuffling
    print("Employee Names: ", employees)
    # output ['Jon', 'Emma', 'Kelly', 'Jason']
    print("Employee Salaries: ", salary)
    # Output [7000, 6500, 9000, 10000]
    # To Shuffle two List at once with the same order
    mapIndexPosition = list(zip(employees, salary))
    random.shuffle(mapIndexPosition)
    # make list separate
    list1_names, list2_salary = zip(*mapIndexPosition)
    # Lists after Shuffling
    print("Employee Names: ", list1_names)
    # Output ('Emma', 'Jon', 'Kelly', 'Jason')
    print("Employee Salary: ", list2_salary)
    # output (6500, 7000, 9000, 10000)
    # Employee name and salary present index 3
    print(list1_names[3], list2_salary[3])
    # Output Jason 10000

    Run

    Shuffling NumPy Multidimensional Array

    To create random numbers, the NumPy module includes the numpy.random library. Here, I demonstrate how to generate a 2D array in Python using the Numpy module. The numpy.random.shuffle() method also allows us to randomly reorder the elements of a multidimensional

    array.

    import numpy as np
    print('Before shuffling 2dimensional array')
    sample_array = np.arange(100, 240, 10)
    sample_array = sample_array.reshape(7, 2)
    print(sample_array)
    print('After shuffling 2dimensional array')
    np.random.shuffle(sample_array)
    print(sample_array)
    

    Produce Results

    :

    Before shuffling 2dimensional array
     [[100 110]
      [120 130]
      [140 150]
      [160 170]
      [180 190]
      [200 210]
      [220 230]]
     After shuffling 2dimensional array
     [[160 170]
      [140 150]
      [200 210]
      [220 230]
      [120 130]
      [100 110]
      [180 190]]

    Shuffle a List to Get the Same Result Every time

    Let’s talk about how to seed the random number generator such that shuffling always yields the same outcome. When we use seed() in conjunction with shuffle(), we always end up with the same randomized set of items. Do you understand how Python’s PRNG works?

    There is no randomness in Python’s random package. It is a deterministic pseudo-random number generator (PRNG). The seed value is the starting point from which the random module generates a random number. The seed value is set to the current system time by default. Changing the seed value allows us to alter the

    output.

    import random
    numbers = [10, 20, 30, 40, 50, 60]
    print("Original list: ", numbers)
    # shuffle 3 times
    for i in range(3):
        # seed PRNG
        random.seed(4)
        # shuffle list
        random.shuffle(numbers)
        print("result list ", numbers)
    

    Produce Results

    :

    Original list:  [10, 20, 30, 40, 50, 60]
    result list  [40, 60, 50, 10, 30, 20]
    result list  [10, 20, 30, 40, 50, 60]
    result list  [40, 60, 50, 10, 30, 20]

    Remark : We are receiving the same list since we are calling the shuffle function with the same seed value. It was only a basic illustration. We need to get the precise seed root number for every given list in order to get the desired result.

    desire.

    Shuffle a String

    Here, we’ll take a look at a Pythonic approach to shuffling a String. A simple list reordering, however, will not do. If you attempt to shuffle a string using the shuffle() function, you will get an error.

    As strings are immutable, you can’t make any changes to them in Python. String is incompatible with random.shuffle(). That is, it cannot take a string as an input. To further grasp this, please refer to the following:

    example.

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

    Run

    In this case, we do have an answer. Many methods exist for randomly rearranging string elements. Goodbye, everyone!

    one.

    Shuffle a String by Converting it to a List

    String to list conversion, followed by random list shuffle, and finally list to string conversion.

    String

    import random
    sample_str = "PYnative"
    # Original string
    print(sample_str)
    # 'PYnative'
    # convert string into list
    char_list = list(sample_str)
    # shuffle list
    random.shuffle(char_list)
    # convert list to string
    final_str = ''.join(char_list)
    # shuffled list
    print(final_str)
    # Output 'tiaeYPvn'
    

    Run

    This method allows us to preserve the integrity of the original string while producing a whole new string that has been randomly rearranged. Also, we don’t have to transform the string to a list in order to receive the jumbled string.

    If you provide it a sample size, the sample() method will return a subset of that sequence. To retrieve three randomly selected characters from a string, use sample(str, 3).

    If we give it a sample size equal to the length of the string, it will return a randomly-generated string.

    characters.

    import random
    sample_str = "PYnative"
    print(sample_str)
    # 'PYnative'
    # shuffle string using random.sample()
    final_str = ''.join(random.sample(sample_str, len(sample_str)))
    print(final_str)
    # Output 'ePtaYivn'

    Run

    Shuffle Range of Integers

    The result of using the range() method is a series of integers.

    If you attempt to execute shuffle(range(10)) you will receive an error since range() does not return the list. The range(10) must be converted to a list before it can be shuffled.

    .

    import random
    # Shuffle a range of numbers
    numbers = list(range(10))
    random.shuffle(numbers)
    print(numbers)
    # Output [1, 7, 0, 3, 2, 9, 6, 8, 4, 5]

    Run

    Shuffle a Dictionary in Python

    Python does not allow for a dictionary to be shuffled. Yet the keys of a may be rearranged in a

    dictionary.

    • Fetch all keys from a dictionary as a list.
    • Shuffle that list and access dictionary values using shuffled keys.
    import random
    student_dict = {'Eric': 80, 'Scott': 75, 'Jessa': 95, 'Mike': 66}
    print("Dictionary Before Shuffling")
    print(student_dict)
    keys = list(student_dict.keys())
    random.shuffle(keys)
    ShuffledStudentDict = dict()
    for key in keys:
        ShuffledStudentDict.update({key: student_dict[key]})
    print("\nDictionary after Shuffling")
    print(ShuffledStudentDict)
    

    Produce Results

    :

    Dictionary before shuffling
    {'Eric': 80, 'Scott': 75, 'Jessa': 95, 'Mike': 66}
    Dictionary after shuffling
    {'Jessa': 95, 'Eric': 80, 'Mike': 66, 'Scott': 75}

    Shuffle a Python generator

    In order to randomly shuffle the sequence, random.shuffle() needs to know its length. TypeError: the object of type ‘generator’ has no len() will be returned if you attempt to shuffle a generator object using it.

    As the generator does not provide a large enough output, we must first transform it into a list before shuffling it.

    it.

    import random
    def sample_generator():
        yield 25
        yield 50
        yield 75
        yield 100
    print("Generator")
    for i in sample_generator():
        print(i, end=", ")
    # Shuffle generator
    newList = list(sample_generator())
    random.shuffle(newList)
    print("\nPrint shuffled generator")
    for i in newList:
        print(i, end=", ")

    Run

    Next Steps

    Please get in touch with me. Let us know what you think of our random.shuffle() article! Maybe I haven’t seen random.shuffle() used elsewhere. Leave a comment and let me know which it is.

    To further your grasp of how to deal with random data in, please attempt to complete the following activity and quiz.

    Python.


    • Python random data generation Exercise

    • Python random data generation Quiz
    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language Python randomshuffle function to shuffle list
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleFree Python eBooks
    Next Article Visualizing Data in Python Using pltscatter

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.