Python: Randomize the order of the values of an list

Python List: Exercise - 221 with Solution

Write a Python program to randomize the order of the values of a list, returning a new list.

  • Uses the Fisher-Yates algorithm to reorder the elements of the list.
  • random.shuffle provides similar functionality to this snippet.

From Wikipedia,
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence—in plain terms, the algorithm shuffles the sequence. The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain. The algorithm produces an unbiased permutation: every permutation is equally likely. The modern version of the algorithm is efficient: it takes time proportional to the number of items being shuffled and shuffles them in place.

Sample Solution:

Python Code:

# Import necessary modules.
from copy import deepcopy
from random import randint

# Define a function called 'shuffle_list' that takes a list 'lst' as an argument.
def shuffle_list(lst):
  # Create a deep copy of the input list to avoid modifying the original list.
  temp_lst = deepcopy(lst)
  # Get the length of the copied list.
  m = len(temp_lst)
  # Perform Fisher-Yates shuffle by iterating over the list and swapping elements randomly.
  while (m):
    m -= 1
    i = randint(0, m)
    temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
  # Return the shuffled list.
  return temp_lst

# Example usage: Shuffle the elements of the list 'nums'.
nums = [1, 2, 3, 4, 5, 6]
print("Original list: ", nums)
print("\nShuffle the elements of the said list:")

Sample Output:

Original list:  [1, 2, 3, 4, 5, 6]

Shuffle the elements of the said list:
[3, 2, 4, 1, 6, 5]


Flowchart: Randomize the order of the values of an list.

Python Code Editor:

Previous: Write a Python program to map the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value.
Next: Write a Python program to get the difference between two given lists, after applying the provided function to each list element of both.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.