How to Create an Array of Random Integers in Python with Numpy



Python


In this article, we show how to create an array of random integers in Python with Numpy.

To create an array of random integers in Python with numpy, we use the random.randint() function.

Into this random.randint() function, we specify the range of numbers that we want that the random integers can be selected from and how many integers we want.

In the code below, we select 5 random integers from the range of 1 to 100.



So, first, we must import numpy as np.

We then create a variable named randnums and set it equal to, np.random.randint(1,101,5)

This produces an array of 5 numbers in which we can select from integers 1 to 100.

1 is inclusive and 101 is exclusive, so the possible integers that we can select from is 1 to 100.

We then display the contents of randnums, which is a random array of 5 integers.

We'll now show one more example.

We're going to create an array of 10 integers that can select from integers to 1-25.

This is shown in the code below.



So now you see an array of 10 random integers.

However, random arrays are not confined to single-dimensional arrays. Arrays can also be multidimensional.

To create random multidimensional arrays, we specify a size attribute and that tells us the size of the array.

For example, if we want an array of 4x5 (4 rows and 5 columns), we specify size= (4,5).

Below is the code to create a random 4 x 5 array in Python.



So this is how you can generate random multidimensional arrays in Python.

And this is all that is required to create an array of random integers in Python with numpy.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...