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.