Hi everyone, We will learn “how to shuffle the list items in Python” in this tutorial.
What is Shuffling?
The term shuffling refers to arranging items randomly. Here we arrange list items randomly for every item the code runs.
Ways to shuffle the list in Python:
There are many ways to Shuffle the list in Python, they are :
- Selecting a random index appending it to the list and deleting the element.
- Using shuffle() in python.
Let’s see each method,
Selecting a random index and appending it to the list:
In this approach, we will select an index of the list randomly using the function randint() . To use randint() function we import the random module.
import random #importing random module
After importing the random module iterate over the list and select a random index using randint() function. The chosen index element is appended to the list from the end and the element is deleted. We repeat the process until all the elements in the list are appended to get the shuffled list every time the code runs.
Code for the above Approach :
import random #importing random module lst=[1,5,4,6,8,7] #Original List print("Original List before Shuffling : ",lst) #printing Original List #Logic to Shuffle the list len_lst=len(lst) for i in range(len_lst): index = random.randint(0, len_lst-1) #randint() randomly chooses a index from 0 to length of list element=lst.pop(index) lst.append(element) print("List after shuffling : ", lst)
Output : Original List before Shuffling : [1, 5, 4, 6, 8, 7] List after shuffling : [8, 7, 6, 5, 4, 1]
Time complexity : O(n)
Space complexity : O(1)
Using the shuffle() method in python:
The shuffle() method is a popular method to shuffle the items in a list in Python. The shuffle() method is implemented by importing a random library and calling the list inside the shuffle() function.
* An important thing while using the shuffle() method is the original order of the list is lost.
import random #importing random lst=[2,5,3,4,8,6] #Original list print("Original list before the shuffle : ", lst) #printing original list random.shuffle(lst) #shuffle() method print("list after shuffling : ", lst) #printing shuffled list
Output : Original list before the shuffle : [2, 5, 3, 4, 8, 6] list after shuffling : [8, 5, 6, 4, 2, 3]
Time complexity : O(n)
Space complexity : O(1)
These are the few methods to shuffle the list items in Python, Hope you learned something new today.
Thank you.