×

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

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

How to Import Files in Python

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 faster way....

3 minutes read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Python slice()

Python slice() class The slice() class return a slice object representing the set of indices specified by range(start, stop, step).  Syntax class slice(stop)          or class slice(start, stop[, step]) Parameter Start: This parameter represents an integer number specifying at...

1 minute read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.

Python Support

Python 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 faster way....

3 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

What is Ipython shell?

IPython is a command shell for computing in multiple programming languages. IPython was developed for python language by Fernando Perez in 2001 as a well-equipped python interpreter that offers shell...

3 minutes read.

What does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in...

3 minutes read.

PyShark in Python

Python: 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 faster way....

4 minutes read.

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL. What is a Database? The places or memory used to secure highly and...

6 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

EDA in Python

The EDA is the exploratory data analysis; the data scientists mainly use the EDA to understand the main features of the data quickly, the variables in python and the relationship...

6 minutes read.