Python | Shuffle a list without recursion

Let us now take a look at all the methods to solve the given problem. In the previous article, you might have seen that we solved this problem using a recursive approach.

Method 1: Using a random() library

import random

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

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

for i in range(len(lst)-1, 0, -1):
   
    j = random.randint(0, i + 1)
    lst[i], lst[j] = lst[j], lst[i]
    
print("Here is the shuffled list: ", lst)

Output:

Enter number of elements : 8
11
6
35
26
95
63
45
2
List entered by the user (without shuffling):  [11, 6, 35, 26, 95, 63, 45, 2]
Here is the shuffled list:  [35, 95, 6, 2, 26, 63, 45, 11]

Explanation:

Here we initialized a for loop to perform the swapping among the elements of the list.

Method 2: Using random. shuffle()

import random

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

print("List entered by the user (without shuffling): ", lst)
random.shuffle(lst)
print ("The shuffled list is : " + str(lst))

Explanation:

Here in this method we simply used the shuffle function of the random library. This is one of the simplest methods to solve this problem.

Method 3: Using random. sample()

import random
lst = []
n = int(input("Enter number of elements : "))
  
for i in range(0, n):
    ele = int(input())
    lst.append(ele) 
print("List entered by the user (without shuffling): ", lst)
result = random.sample(lst, len(lst))
print ("The shuffled list is : ", result)

Explanation:

Here in this method, we used the sample function of the random library. The built-in function sample() of the random module in Python returns a certain length list of objects selected from the sequence, such as a list, tuple, string, or set. used for replacement-free random sampling.

Method 3: Using the randint() function

import random
lst = []
n = int(input("Enter number of elements : "))
  
for i in range(0, n):
    ele = int(input())
    lst.append(ele) 
print("List entered by the user (without shuffling): ", lst)
n = len(lst)
for i in range(n):
    j = random.randint(0, n-1)
    element=lst.pop(j)
    lst.append(element)
print ("The shuffled list is : ", lst)

Output:

Enter number of elements : 6
1
2
3
4
5
6
List entered by the user (without shuffling):  [1, 2, 3, 4, 5, 6]
The shuffled list is :  [2, 3, 5, 4, 1, 6]

Explanation:

Here we used the randint() function to generate a random set of integers in between the range of 0 to the length of the list. This function will generate the random integer and that integer will be taken as an index to pop out the elements in the list.

Here is the end of our article. We have also covered the simplest and the most complicated methods to help you understand various concepts involved in Problem Solving.

Share:

Author: Ayush Purawr