Python | Shuffle a list using recursion

Here is the solution to shuffle list elements using recursion. We will go through all the methods available using which we can solve this problem.

from random import choice

def shuffle(A, left=None, done=0):
    if left is None:
        A = A[::2]+A[1::2]  
        left = len(A[1::2])  
    if done > left:
        return A  
    if done < left:
        rLeft = choice(range(done, left))       
        A[done], A[rLeft] = A[rLeft], A[done]
    if left+done < len(A):
        rRight = choice(range(left+done, len(A)))     
        A[-1-done], A[rRight] = A[rRight], A[-1-done]
    return shuffle(A, left, done+1)                

lst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
    ele = int(input())

print("List entered by the user (without shuffling): ", lst)

print("Here is the shuffled list: ", shuffle(lst))


Enter number of elements : 6
List entered by the user (without shuffling):  [11, 12, 13, 14, 15, 16]
Here is the shuffled list:  [11, 13, 15, 14, 16, 12]


Here we took the two inputs from the user, n and a list, where n represents a number of elements in the list. We took the left variable as None. Now we used the conditional to check if the left is None then we partition the list in such a way that A[::2] will give us the list as output wherein the alternate elements of the list will be there and the output of A[1::2] is a list starting from the element at index 1 and then the alternate elements. Now we compute the length of the list that is the output of A[1::2].

Now we check if done is greater than left then we simply return A, else, we move on to the next conditional we have used the choice function to randomly choose an integer and store it in rLeft. We then use the concept of swapping using this line of code A[done], A[rLeft] = A[rLeft], A[done]. If the condition i.e. done < left is not satisfied then we move on to the very last condition.

left+done < len(A) inside this if statement, we have called the shuffle function that will again call the function and the code flow will continue on the basis of different conditional statements.

This is one of the recursive approaches with which we can solve this problem. Here is the end of our article on Python Programs to shuffle a list using recursion

Avatar of Dhvanil V

Author: Dhvanil V