Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python | Ways to shuffle a list

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Shuffling a sequence of numbers have always been an useful utility and the question that has appeared in many company placement interviews as well. Knowing more than one method to achieve this can always be a plus. Let’s discuss certain ways in which this can be achieved.
Method #1 : Fisher–Yates shuffle Algorithm
This is one of the famous algorithms that is mainly employed to shuffle a sequence of numbers in python. This algorithm just takes the higher index value, and swaps it with current value, this process repeats in a loop till end of the list. 
 

Python3




# Python3 code to demonstrate
# shuffle a list
# using Fisher–Yates shuffle Algorithm
 
import random
 
# initializing list
test_list = [1, 4, 5, 6, 3]
 
# Printing original list
print ("The original list is : " + str(test_list))
 
# using Fisher–Yates shuffle Algorithm
# to shuffle a list
for i in range(len(test_list)-1, 0, -1):
     
    # Pick a random index from 0 to i
    j = random.randint(0, i + 1)
   
    # Swap arr[i] with the element at random index
    test_list[i], test_list[j] = test_list[j], test_list[i]
     
# Printing shuffled list
print ("The shuffled list is : " +  str(test_list))


Output: 

The original list is : [1, 4, 5, 6, 3]
The shuffled list is : [4, 3, 1, 5, 6]

 

  
Method #2 : Using random.shuffle() 
This is most recommended method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list. Drawback of this is that list ordering is lost in this process. Useful for developers who choose to save time and hustle.
 

Python3




# Python3 code to demonstrate
# shuffle a list
# using random.shuffle()
 
import random
 
# initializing list
test_list = [1, 4, 5, 6, 3]
 
# Printing original list
print ("The original list is : " + str(test_list))
 
# using random.shuffle()
# to shuffle a list
random.shuffle(test_list)
 
# Printing shuffled list
print ("The shuffled list is : " +  str(test_list))


Output: 

The original list is : [1, 4, 5, 6, 3]
The shuffled list is : [5, 6, 4, 3, 1]

 

  
Method #3 : Using random.sample() 
This is quite a useful function, better than the shuffle method used above in aspect that it creates a new shuffled list and returns it rather than disturbing the order of original list. This is useful in cases we require to retain the original list.
 

Python3




# Python3 code to demonstrate
# shuffle a list
# using random.sample()
 
import random
 
# initializing list
test_list = [1, 4, 5, 6, 3]
 
# Printing original list
print ("The original list is : " + str(test_list))
 
# using random.sample()
# to shuffle a list
res = random.sample(test_list, len(test_list))
 
# Printing shuffled list
print ("The shuffled list is : " +  str(res))


Output: 

The original list is : [1, 4, 5, 6, 3]
The shuffled list is : [5, 3, 6, 1, 4]

 

Method 4:

In this method we select a index randomly and append that element at that index to the list.

Python3




import random
 
# Assign array
arr = [1, 2, 3, 4, 5, 6]
 
# Display original array
print("Original List: ", arr)
 
# Get length of List
n = len(arr)
 
#repeat the following for n number of times
for i in range(n):
    #select an index randomly
    j = random.randint(0, n-1)
    #delete the element at that index.
    element=arr.pop(j)
    #now append that deleted element to the list
    arr.append(element)
print("Shuffled List: ",arr)


Output

Original List:  [1, 2, 3, 4, 5, 6]
Shuffled List:  [4, 5, 3, 2, 6, 1]

Using itertools.permutations() function:

Approach:

This method generates all possible permutations of the original list using the itertools.permutations() function, and then selects a random one.

Python3




import random
import itertools
 
lst = [1, 4, 5, 6, 3]
permutations = list(itertools.permutations(lst))
shuffled_lst = random.choice(permutations)
 
print("Shuffled list:", shuffled_lst)


Output

Shuffled list: (5, 4, 1, 6, 3)

Time Complexity: O(n!) where n is the length of the list, due to the generation of all possible permutations.

Space Complexity: O(n!) as all possible permutations are generated and stored in a list.

Using numpy:

Algorithm:

  1. Import the required modules Initialize the list to be shuffled.
  2. Use reduce() function from the functools module to repeatedly apply the np.random.permutation() function to the list
  3. The reduce function takes 3 arguments – a lambda function, a range object and the list to be shuffled
  4. The lambda function takes two arguments – an accumulator and an iterator variable, and applies np.random.permutation() to the accumulator.
  5. Reduce function returns the shuffled list and Print the shuffled list.

Python3




import numpy as np
from functools import reduce
 
# initializing list
test_list = [1, 4, 5, 6, 3]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# using reduce() and numpy
# to shuffle a list
res = reduce(lambda acc, _: np.random.permutation(acc),
             range(len(test_list)), np.array(test_list))
 
# Printing shuffled list
print("The shuffled list is : " + str(res.tolist()))
 
# This code is contributed by Jyothi pinjala.


Output:

The original list is : [1, 4, 5, 6, 3]
The shuffled list is : [3, 6, 1, 5, 4]

Time Complexity:
The time complexity of the reduce() function depends on the number of iterations, which is equal to the length of the list. The time complexity of np.random.permutation() is O(n) where n is the length of the input array. Therefore, the time complexity of this code is O(n^2).

Space Complexity:
The space complexity of this code depends on the size of the list. The list is stored in memory along with a few additional variables used by the reduce() function. Therefore, the space complexity is O(n).
has context menu


My Personal Notes arrow_drop_up
Last Updated : 05 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials