×

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of items like a list and Numpy array. The shuffle function cannot reorganize immutable data sets such as a string and tuple. This shuffle( )  method is generally used in password generators; we can randomly generate the password through this method. The shuffle( ) function does not return any value but changes the position of the elements in the mutable sequence.

Syntax :

random.shuffle(x, function)

Parameters:

  • x-The x can be any mutable sequence of items such as a list and Numpy array.
  • function- This is an optional parameter, and by default, it is set to random this must return a value between 0 and 1

Return: This function should not return any value, but it only changes the position of the elements in a mutable sequence.

Shuffling a List

The list can be rearranged by following the steps in python-

  • Create a list-
    We need to create a list in python using the list( ) function, or we can input the list manually
  • Importing  the random module-
    We need to import the random module to shuffle the list randomly.
  • Use shuffle( ) function –
    Here, we use the random.shuffle(list) function to shuffle the list. This shuffle function does not return any value but changes the positions of the elements in the original list.
  • Print the shuffled list-
    As we know that the shuffle( ) function does not return any value, we need to use the print( ) function to display the shuffled list.
  • Return the shuffled list instead of modifying the original list-
    Generally, we require shuffled and original lists in many operations. So, we can make the copy of the original list using the copy ( ) function before shuffling then we can shuffle the list to get the shuffled list.
  • Customize the shuffle if required-|
    Generally, the function in the function in the shuffle is set to random. Still, we can also customize the function in place of random we can pass a custom function, which will pass the instructions to the shuffle( ) to randomize the list items.

Example-

import random
#original list
list=[4,5,23,45,67,89,12]
#displaying the original list
print(list)
#shuffling the list
random.shuffle(list)
#displaying the shuffled list.
print(list)

Output:

#original list-
[4, 5, 23, 45, 67, 89, 12]	
#shuffled list-
[23, 67, 89, 4, 12, 5, 45]

Here, we can observe that the position of the elements is changed in the shuffled list after performing the shuffle( ) operation on the original list.

Shuffling Two Lists once in the Same Order

In this operation, we will see if we want to shuffle two lists and if we want to maintain the same shuffle order. Now let us consider an example of one list consisting of the student's names and the other list consisting of the student's marks; here, we will randomly shuffle both the lists by maintaining the same order.

Example

import random
# list consisting of names of students
students= [‘Nihaas’, ‘Nikitha’, ‘Bunty’, ‘Rohit’, ‘Rishika’, ‘Deeraj’, ‘Kavlas’]
#list consisting of marks obtained by students
marks= [96, 93, 84, 85, 95, 76, 80]
#displaying student's list before shuffling.
print(students)
#displaying marks list before shuffling.
print(marks)


#shuffling the two lists at once in the same order
mapIndexPosition = list(zip(students, marks))
random.shuffle(mapIndexPosition)
#making the lists separate
list_students, list_marks = zip(*mapIndexPosition)


#displaying lists after shuffling
print(list_students)
print(list_marks)

Output:

 [‘Nihaas’, ‘Nikitha’, ‘Bunty’, ‘Rohit’, ‘Rishika’, ‘Deeraj’, ‘Kavlas’]
 [96, 93, 84, 85, 95, 76, 80]
[‘Nikitha’, ‘Rohit’, ‘Deeraj’, ‘Bunty’, ‘Kavlas’, ‘Nihaas’, ‘Rishika’]
 [93, 85, 76, 84, 80, 96, 95]

Shuffling a Numpy Multidimensional Array

To shuffle the numpy arrays first, we need to import the numpy library in which it has a numpy.random module to generate the random data using the numpy.random.shuffle( ) function, we can reorder the elements in the multidimensional array.

Example

import numpy as np
#Original shuffling two-dimensional array
original_array = np.arange(50, 130, 10)
original_array = original_array.reshape(4, 2)
print(original_array)


# shuffled two-dimensional array
np.random.shuffle( original_array )
print( original_array )

Output

#Original two-dimensional array
[[50 60]
 [70 80]
 [90 100]
 [110 120]]
 #Shuffled two-dimensional array
   [[90 100]
  [110 120]
    [70 80]
    [50 60]]

Here, we can observe that the elements in the numpy array are randomly reorganized, and the shuffled list is obtained.


Related Topics

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Gethostbyname() function in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Compound Interest GUI Calculator using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

Python String splitlines() method

Python String splitlines() method The string.splitlines() method in Python splits the specified string and returns a list of the lines in the string, breaking at line boundaries.  Syntax splitlines([keepends]) Parameter keepends(optional): This parameter specifies if...

1 minute read.