w3resource

NumPy: Shuffle numbers between 0 and 10


6. Shuffle Numbers 0-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.

For more Practice: Solve these Related Problems:

  • Shuffle the integers 0 through 10 using np.random.permutation and verify that the result is a complete permutation.
  • Create a function that shuffles an array in place and returns a new array with the same elements in random order.
  • Generate two different random shuffles of the numbers 0 to 10 and compare them to ensure variability.
  • Simulate multiple shuffles and compute the frequency of each number’s occurrence in the first position.

Go to:


PREV : Extract First 5 Rows of 10x4 Array.
NEXT : Normalize a 3x3 Matrix.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.