×

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

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

Python: SetBitmap() function in wxPython

SetBitmap() function In the last tutorial, we have discussed about the GetLabelText() function of wx.MenuItem class which is one of the important function of this class. Now, in this tutorial, we...

6 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

Python memoryview() Function

Python memoryview() Function The memoryview() function in Python returns a memory view object from a specified object. Syntax memoryview(obj) Parameter obj: This parameter represents a Bytes object or a bytearray object. Return This function returns a “memory view” object...

1 minute read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

CSV Module In Python

Introduction CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores...

5 minutes read.

Io stringio Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

7 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Python tuple() function

Python tuple() function The tuple() function in Python creates a tuple object. Syntax tuple([iterable]) Parameter Iterable: This parameter represents a sequence, collection or an iterator object. Return This function returns a tuple object. Example 1 # Python Program explaining #...

1 minute read.

Python Trigonometric Functions

Before jumping right into the functions and how to use them we need to know what do trigonometric functions mean and how many functions does python has. What are Trigonometric functions? Trigonometric...

3 minutes read.