w3resource

NumPy: Shuffle numbers between 0 and 10


Write a NumPy program to shuffle numbers between 0 and 10 (inclusive).

Sample Solution:

Python Code :

# Importing the NumPy library as np
import numpy as np

# Generating an array 'x' with numbers from 0 to 9 using np.arange()
x = np.arange(10)

# Shuffling the elements of the array 'x' in-place using np.random.shuffle()
np.random.shuffle(x)

# Printing the shuffled array 'x'
print(x)

# Generating a permutation of numbers from 0 to 9 using np.random.permutation()
# and printing the result
print("Same result using permutation():")
print(np.random.permutation(10))

Sample Output:

[2 7 1 5 3 9 0 4 6 8]                                                  
Same result using permutation():                                       
[8 9 0 4 7 3 1 6 5 2]

Explanation:

In the above code –

x = np.arange(10): This code creates an array x of integers from 0 to 9 using the np.arange() function. The input argument 10 specifies that the array should contain integers from 0 up to, but not including, 10.

np.random.shuffle(x): This code shuffles the elements in the x array in-place (i.e., without creating an array) using the np.random.shuffle() function. The original order of the elements in the array x is randomly assigned.print(np.random.permutation(10)): This code generates an array containing a random permutation of integers from 0 to 9 using the np.random.permutation() function. The input argument 10 specifies that the output array should contain integers from 0 up to, but not including, 10. The function returns an array without modifying the input integer.

Finally, the print() function displays the newly created array.

Pictorial Presentation:

NumPy Random: Shuffle numbers between 0 and 10.

Python-Numpy Code Editor: