Shuffle an array in Python
Last Updated :
15 Sep, 2022
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.
Using shuffle() method from numpy library
Here we are using the shuffle() method from numpy library to shuffle an array in Python.
Python3
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
print("Original array: ", arr)
np.random.shuffle(arr)
print("Shuffled array: ", arr)
|
Output
Original array: [1 2 3 4 5 6]
Shuffled array: [4 1 5 3 2 6]
Using shuffle() method from Random library to shuffle the given array.
Here we are using shuffle method from the built-in random module to shuffle the entire array at once.
Python3
import random
import array
arr = np.array([1, 2, 3, 4, 5, 6])
print("Original array: ", arr)
random.shuffle(arr)
print("Shuffled array: ", arr)
|
Output:
Original array: [1 2 3 4 5 6]
Shuffled array: [4 5 2 6 1 3]
Using sample() method to shuffle an array
Here we are using the sample method from the random library to shuffle an array.
Python3
import random
import array
arr = array.array('q', [1, 2, 3, 4, 5, 6])
print("Original array: ", arr)
arr = array.array('q', random.sample(list(arr), 6))
print("Shuffled array: ", arr)
|
Output:
Original array: array('q', [1, 2, 3, 4, 5, 6])
Shuffled array: array('q', [6, 3, 2, 1, 5, 4])
Selecting random indices and swapping them
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 random
import array
class Shuffler(object):
def __init__(self, arr):
self.temp_array = arr
self.indices = [index for index in range(len(arr))]
def shuffle(self):
if not len(self.temp_array):
return []
for i in range(random.randint(int(len(self.temp_array)/2),
len(self.temp_array))):
i = random.choice(self.indices)
j = random.choice(self.indices)
self.temp_array[i], self.temp_array[j] = self.temp_array[j],
self.temp_array[i]
return self.temp_array
arr = array.array('q', [1, 2, 3, 4, 5, 6])
ob = Shuffler(arr)
print("Original array: ", arr)
print("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])
Using Fisher-Yates Shuffle Algorithm to shuffle an array
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 random
import numpy as np
def shuffler (arr, n):
for i in range(n-1,0,-1):
j = random.randint(0,i+1)
arr[i],arr[j] = arr[j],arr[i]
return arr
arr = np.array([1, 2, 3, 4, 5, 6])
print("Original array: ",arr)
n = len(arr)
print("Shuffled array: ",shuffler(arr, n))
|
Output:
Original array: [1 2 3 4 5 6]
Shuffled array: [6 1 2 3 4 5]
Selecting random indices and storing in a new list
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)-1
for i in range(n):
random_index = random.randint(0, n)
temp = arr.pop(random_index)
arr.append(temp)
print(arr)
|
Output:
[3, 5, 4, 6, 2, 1]
Similar Reads
Shuffle an array in Python
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. Using shuffle() method from numpy library Here we ar
4 min read
Python | Reverse a numpy array
As we know Numpy is a general-purpose array-processing package that provides a high-performance multidimensional array object, and tools for working with these arrays. Let's discuss how can we reverse a Numpy array. Using flip() function to Reverse a Numpy array The numpy.flip() function reverses th
2 min read
Shuffling Images in Python
In this article, we will learn how to shuffle an image using the image_shuffler package in Python. Image_shuffler package in Python This library is used to split an image into 'n' no. of parts and then shuffle it. Before going to dive into the topic first, we need to set up the python environment an
2 min read
Declaring an Array in Python
An array is a container used to store the same type of elements such as integer, float, and character type. An Array is one of the most important parts of data structures. In arrays, elements are stored in a contiguous location in a memory. We can access the array elements by indexing from 0 to (siz
4 min read
Python | Ways to shuffle a list
In this article, we will explore various methods to shuffle a list in Python. The simplest method is to use random.shuffle() to shuffle a list. Using random.shuffle()The random.shuffle() function is simplest way to shuffle a list in-place. It directly modifies the list and doesn't return a new list.
2 min read
Shuffle a deck of card with OOPS in Python
The objective is to distribute a deck of cards among two players. The code for the Shuffle Deck of Cards in Python can be used to shuffle the cards. The shuffle method, which is a built-in feature of the random library, is used to mix and randomize the order of the data before printing it. Prerequis
3 min read
random.shuffle() function in Python
The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling a list of objects means changing the position of the elements of the sequence using Python. Syntax of random.shuffle() The order of the items in a sequence, such as a list, is rearranged using
2 min read
numpy.random.shuffle() in python
With the help of numpy.random.shuffle() method, we can get the random positioning of different integer values in the numpy array or we can say that all the values in an array will be shuffled randomly. Syntax : numpy.random.shuffle(x) Return : Return the reshuffled numpy array. Example #1 : In this
1 min read
Ways to shuffle a Tuple in Python
Shuffling numbers can sometimes prove to be a great help while programming practices. This process can be directly implemented on the data structures which are mutable like lists, but as we know that the tuples are immutable so it cannot be shuffled directly. If you'll try to do so as done in the be
2 min read
Python Arrays
Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences: Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
10 min read