How to use sample() method to shuffle an array In Python

Here we are using the sample method from the random library to shuffle an array.

Python3




# Import required module
import random
import array
 
# Assign array
# here q indicates that the array
# contains signed integer
arr = array.array('q', [1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ", arr)
 
# Shuffle array
# Here sample() returns a list, so we
# are typecasting list into array
arr = array.array('q', random.sample(list(arr), 6))
 
# Display shuffled array
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])

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.

Similar Reads

Using shuffle() method from numpy library

Here we are using the shuffle() method from numpy library to shuffle an array in Python....

Using shuffle() method from Random library to shuffle the given array.

...

Using sample() method to shuffle an array

Here we are using shuffle method from the built-in random module to shuffle the entire array at once....

Selecting random indices and swapping them

...

Using Fisher-Yates Shuffle Algorithm to shuffle an array

Here we are using the sample method from the random library to shuffle an array....

Selecting random indices and storing in a new list

...