Python Random Number – Generate Random Numbers With NumPy

1. Objective – Python Random Number

Today, in this Python tutorial, we will talk about Python Random Number. Moreover, we will see ways to generate Random Number in Python. Also, we will discuss generating Python Random Number with NumPy. At last, we will see Import Random Python with the example.
So, let’s begin with Python Random Number.

Python Random Number

Python Random Number – Generate Random Numbers With NumPy

2. Need of Python Random Number

A Random Number in Python is any number in a range we decide. From initializing weights in an ANN to splitting data into random train and test sets, the need for generating random numbers is apparent. Another use-case could be the random shuffling of a training dataset in stochastic gradient descent. So today, we will discuss pseudorandom generators in Python. We will also try doing that with the standard Python library and with NumPy.

3. How to Generate Python Random Number?

What we really generate is pseudorandom numbers. There are numbers that appear nearly random but are actually something we generate with a deterministic process.

How to Generate Python Random Number?

A process of Generating Python Random Number

You must read about Python Libraries
Python uses the Mersenne Twister pseudorandom number generator. The process of generating random numbers involves deterministically generating sequences and seeding with an initial number. The default for the seed is the current system time in seconds/ milliseconds. A different seed will produce a different sequence of random numbers.

a. Import Python Random

Before we can begin, let’s first import the module random from the Python Standard Library. You can directly import it-
import random
To import a piece of functionality from it- say, random, you can:
from random import random
Or for seed, you can:
from random import seed

b. Random Floating Point Numbers

Let’s take an example of generation Python Random Number.

>>> from random import seed
>>> from random import random
>>> seed(7)
>>> random(),random(),random(),random()

(0.32383276483316237, 0.15084917392450192, 0.6509344730398537, 0.07243628666754276)
Have a look at Python Packages
Works for us. Now, what if we reseed to the same value and call the random() functions/methods again?

>>> seed(7)
>>> random(),random(),random(),random()

(0.32383276483316237, 0.15084917392450192, 0.6509344730398537, 0.07243628666754276)
You’ll find it gives us the same thing as it did earlier.

  • Working with minimum values and multiplying the floats-

Some days, you may not want to generate Random Number in Python values between 0 and 1. In the following piece of code, 2 is the minimum value, and we multiple the random number generated by 10.

>>> seed(7)
>>> 2+10*random()

5.238327648331624

c. Python Random Integers

We use the randint() function to get integers instead, randomly. It takes two arguments- the start and the top, and then draws a random value from a uniform distribution. Each value has an equal chance of being picked.

>>> from random import randint
>>> seed(7)
>>> randint(0,9),randint(0,9),randint(0,9)

(5, 2, 6)
We asked for three random values, this gave us 5, 2, and 6.
Let’s learn Python Debugger

d. Getting Integers Randomly from a Range

randrange() randomly selects an element from range(start,stop,step).

>>> from random import randrange
>>> randrange(-2,4)

-1

>>> randrange(-2,4)

0

>>> randrange(-2,4)

1

>>> randrange(-2,4)

-1

>>> randrange(-2,4)

2

>>> randrange(-2,4)

-2

e. Random Gaussian Values

The gauss() function takes in two arguments- the mean and the standard deviation. This gives us a real-valued distribution.

>>> from random import gauss
>>> seed(7)
>>> gauss(0,1),gauss(0,1),gauss(0,1)

(-0.2558802884476004, 0.511431512516514, -0.2260961647831047)

f. Choosing Randomly From Lists

It is possible to randomly pick values from our own custom lists. We have the choice() function/method for this.

>>> list=[2,4,3,9,6,2,1,0,7,4,3,5,3,6,8]
>>> from random import choice
>>> seed(7)
>>> choice(list),choice(list),choice(list),choice(list),choice(list),choice(list)

(2, 3, 1, 3, 2, 4)
For a choice of multiple values, you can use choices() instead.
Let’s take a tour to Python Network Programming

>>> from random import choices
>>> choices(list,k=4)

[7, 2, 9, 7]

g. Randomly Choosing a Subset from a List

Once sample() puts an item from a list into the sublist, it does not add it back to the original list for picking from. This is selection without replacement. Note that this does not modify the original list. This function/ method also takes the size of the subset to create.

>>> list

[2, 4, 3, 9, 6, 2, 1, 0, 7, 4, 3, 5, 3, 6, 8]

>>> from random import sample
>>> sample(list,6)

[6, 7, 4, 2, 4, 2]

h. Shuffling a List Randomly

We can shuffle a list like a deck of cards with the shuffle() function/ method. This shuffles the list in-place. In other words, it does not need to create a new list to put shuffled items into one by one.

>>> list

[2, 4, 3, 9, 6, 2, 1, 0, 7, 4, 3, 5, 3, 6, 8]

>>> from random import shuffle
>>> shuffle(list)
>>> list

[6, 3, 2, 3, 6, 5, 0, 3, 4, 1, 4, 2, 9, 7, 8]
Note that this modifies the list.
Let’s revise Image Processing with NumPy and SciPy

Python Interview Questions

4. How to Generate Python Random Number with NumPy?

With the seed() and rand() functions/ methods from NumPy, we can generate random numbers. The functionality is the same as above.

>>> from numpy.random import seed
>>> from numpy.random import rand
>>> seed(7)
>>> rand(3)

array([0.07630829, 0.77991879, 0.43840923])

>>> seed(7)
>>> rand(3)

array([0.07630829, 0.77991879, 0.43840923])
So, this was all about Generating Python Random Number. Hope you like our explanation.

5. Conclusion – Python Random Number

Now you know how to generate random numbers in Python. We used two modules for this- random and numpy. Moreover, we discussed the process of generating Python Random Number with examples. Tell us what you think about the article Python Random Number. Got a topic you want us to write us on? Let us know in the comments.
See also – 
Python Unit testing
For reference

7 Responses

  1. Lalit Siraswa says:

    from numpy.random import rand

    Traceback (most recent call last):
    File “”, line 1, in
    from numpy.random import rand
    ModuleNotFoundError: No module named ‘numpy’

    • DataFlair Team says:

      Hi Lalit,
      Thanks for connecting DataFlair. You are getting an error because you didn’t install numpy. We recommend you to install numpy first then run this code on it. Furthermore, if you will get a query, you can write us back.
      Regards,
      DataFlair

  2. Manish Jangid says:

    Please explain the mean of seed(7) in random floating point numbers.

    • DataFlair Team says:

      Hello Manish,
      Seed(7) is to provide a starting value for generating a random number in Python. In other words, it is to feed the generator.
      Hope, it helps!
      Regards,
      DataFlair

  3. Seema says:

    Hi , Related to Seed(7), I understood that it is for getting same random value again and again.But what is the significance of (7) as I am getting same result with any number.Also thanks for the great platform to learn.I have just started to learn Python for Data Analysis as complete novice.

  4. Semih says:

    Hello. As other friends had, I have same question with “seed”
    Do we have to use it? instead of “seed”, i can create random number like that

    from numpy.random import rand
    rand() #this works. So why should I add “seed” ?

    Thank you for tutorials. They are really detailed. I like your work!

  5. Aditya says:

    What does seed mean, you use seed(7) in your code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.