Shuffle an array in Python

05 Sep, 2021
Shuffling a sequence of numbers have always been a useful utility, it is nothing but rearranging the elements in an array. Knowing more than one method to achieve this can always be a plus. Let’s discuss certain ways in which this can be achieved.
Method 1: In this method we use shuffle() method from numpy library. 
Python3
# Import required moduleimport numpy as np # Assign arrayarr = np.array([1, 2, 3, 4, 5, 6]) # Display original arrayprint("Original array: ", arr) # Shuffle arraynp.random.shuffle(arr) # Display shuffled arrayprint("Shuffled array: ", arr)
Output
Original array:  [1 2 3 4 5 6]
Shuffled array:  [4 1 5 3 2 6]
Method 2: In this method we will use shuffle() method from Random library to shuffle the given array.
Python3
# Import required moduleimport randomimport array # Assign arrayarr = np.array([1, 2, 3, 4, 5, 6]) # Display original arrayprint("Original array: ", arr) # Shuffle arrayrandom.shuffle(arr) # Display shuffled arrayprint("Shuffled array: ", arr)
Output:
Original array:  [1 2 3 4 5 6]
Shuffled array:  [4 5 2 6 1 3]
Method 3: In this method we will use sample() method from Random library to shuffle the given array.
Python3
# Import required moduleimport randomimport array # Assign array# here q indicates that the array# contains signed integerarr = array.array('q', [1, 2, 3, 4, 5, 6]) # Display original arrayprint("Original array: ", arr) # Shuffle array# Here sample() returns a list, so we# are typecasting list into arrayarr = array.array('q', random.sample(list(arr), 6)) # Display shuffled arrayprint("Shuffled array: ", arr)
Output:
Original array:  array('q', [1, 2, 3, 4, 5, 6])
Shuffled array:  array('q', [6, 3, 2, 1, 5, 4])
Method 4: In this method we will select 2 indices randomly and then swap them. This process will be randomly repeated up to n/2 to n times, Where n is the length of array.
Python3
# Import required moduleimport randomimport array   # Create class to shuffle arrayclass Shuffler(object):     # Constructor    def __init__(self, arr):         # Initializes the temp_array        self.temp_array = arr         # All the indices are stored in indices list        self.indices = [index for index in range(len(arr))]     # method to shuffle array    def shuffle(self):         # if length of array is zero empty array is returned.        if not len(self.temp_array):            return []         # The below swapping process is repeated randomly in range of        # half of length of array to length of the array, in this case,        # it is repeated randomly in between 3 to 6 times.        for i in range(random.randint(int(len(self.temp_array)/2), len(self.temp_array))):             # randomly choses two indices that is i, j from indices list            i = random.choice(self.indices)            j = random.choice(self.indices)             # swapping the elements present at i,j indices.            self.temp_array[i], self.temp_array[j] = self.temp_array[j], self.temp_array[i]        return self.temp_array   # Driver code # Assign arrayarr = array.array('q', [1, 2, 3, 4, 5, 6]) # Create Object of Shuffler classob = Shuffler(arr) # Display original arrayprint("Original array: ", arr) # Shuffle method is calledprint("Shuffled array: ", ob.shuffle())
Output:
Original array:  array('q', [1, 2, 3, 4, 5, 6])
Shuffled array:  array('q', [1, 6, 3, 2, 4, 5])
Method 5: This is the one of the most efficient methods, it is the Fisher–Yates shuffle Algorithm. Below program will help you understand this algorithm.
Python3
# Import required moduleimport randomimport numpy as np  # A function to generate a random# permutation of arraydef shuffler (arr, n):         # We will Start from the last element    # and swap one by one.    for i in range(n-1,0,-1):                 # Pick a random index from 0 to i        j = random.randint(0,i+1)                 # Swap arr[i] with the element at random index        arr[i],arr[j] = arr[j],arr[i]    return arr       # Driver code     # Assign arrayarr = np.array([1, 2, 3, 4, 5, 6]) # Display original arrayprint("Original array: ",arr) # Get length of arrayn = len(arr) # Use shuffler() function to get shuffled arrayprint("Shuffled array: ",shuffler(arr, n))
Output:
Original array:  [1 2 3 4 5 6]
Shuffled array:  [6 1 2 3 4 5]
Method 6:
In this method we will randomly select an index and append it to end of the array. this will be repeated for n time where n is length of array.
Python3
import random arr=[1,2,3,4,5,6]n=len(arr)-1for i in range(n):    random_index = random.randint(0, n)    temp = arr.pop(random_index)    arr.append(temp)print(arr)
[2, 3, 6, 1, 5, 4]
anikaseth98
sagartomar9927
pulamolusaimohan
Python-array
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function