Random Numbers in Python

Abhishek Sharma Last Updated : 21 Oct, 2024
7 min read

Randomness is incredibly valuable in the world of programming for use in simulations, games, cryptography and data analysis. Extremely, Python with the broad standard library find numerous methods for creating random numbers well-mannered and effectively. What more do you want: Random integers, floating point numbers or even selecting random items from a list – Python has it all. This paper aims at discussing the different approaches which can be used to generate random numbers in the Python programming language with special regard to the random module which comes with the language. By the time you complete the whole of this guide you should have gained some understanding as to how to use randomness in your python projects.

Learning Objectives

  • Understand the concept of randomness in programming.
  • Utilize the Python random module to generate different types of random numbers.
  • Apply random number generation in practical scenarios such as simulations and games.

Generating Random Numbers in Python using the Random Library

Random number generation in Python is a simple process that should be included in every programmer’s repertoire as it will assist him or her in future projects, be they games, simulation, visualization techniques and or data analysis. The random module is a standard Python library containing a group of functions to generate random integers or float, or select elements from sequences such as list, etc. Another bonus of Python is the involvement of randomness in your code by using random integers by randint(), floats within a range by uniform() and randomly selecting between sequence with choice(). Proficiency in these skills enables the developers to design the complex and random type of applications that would really help the consumers to have an exciting experience while at the same time enable modeling of the real word.

Note: Do not use the random module for generating random numbers for security purposes. For security and cryptographic uses, you can use the secrets module which uses true-random number generators (TRNG).

Seeding Random Numbers

The random module has a seed that helps the random number generator to start. This seed value is used in order to generate what is called a deterministic sequence of random numbers that is, when using the same seed number the program will produce the same continued sequence of random numbers. These are known as pseudo-random numbers.

Let’s understand it with an example:

import random

print('Random Number 1=>',random.random())
print('Random Number 2=>',random.random())

Here, I am using the random() function which generates a random number in the range [0.0, 1.0]. Notice here that I haven’t mentioned the value of the seed. By default, the current system time in milliseconds is used as a seed. Let’s take a look at the output.

output

Both numbers are different because of the change in time during execution from the first statement to the second statement. Let’s see what happens if we seed the generators with the same value:

random.seed(42)
print('Random Number 1=>',random.random())

random.seed(42)
print('Random Number 2=>',random.random())
Seeding Random Numbers

We get the same numbers here. That’s why pseudo-random number generators are deterministic and not used in security purposes because anyone with the seed can generate the same random number.

Generating Random Numbers in a Range

So far, we know about creating random numbers in the range [0.0, 1.0]. But what if we have to create a number in a range other than this?

One way is to multiply and add numbers to the number returned by the random() function. For example, random.random() * 3 + 2 will return numbers in the range [2.0, 5.0]. However, this is more of a workaround, not a straight solution.

Don’t worry! The random module has got your back here. It provides uniform() and randint() functions that we can use for this purpose. Let’s understand them one by one.

uniform()

The uniform() function of the random module takes starting and ending values of a range as arguments and returns a floating-point random number in the range [starting, ending]:

print('Random Number in range(2,8)=>', random.uniform(2,8))
uniform()

randint()

This function is similar to the uniform() function. The only difference is that the uniform() function returns floating-point random numbers, and the randint() function returns an integer. It also returns the number in the range [starting, ending]:

print('Random Number in a range(2,8)=>', random.randint(2,8))
randint()

Picking Up Randomly From a List

choice() & choices() are the two functions provided by the random module that we can use for randomly selecting values from a list. Both of these functions take a list as an argument and randomly select a value(s) from it. Can you guess what the difference between choice() and choices() is?

choice() only picks a single value from a list whereas choices() picks multiple values from a list with replacement. One fantastic thing about these functions is that they work on a list containing strings too. Let’s see them in action:

a=[5, 9, 20, 10, 2, 8]
print('Randomly picked number=>',random.choice(a))
print('Randomly picked number=>',random.choices(a,k=3))
random numbers python

As you can see, choice() returned a single value from a and choices() returned three values from a. Here, k is the length of the list returned by choices().

One more thing you can notice in the responses returned by choices() is that each value occurs only once. You can increase the probability of each value being picked by passing an array as weights to the choices() function. So, let’s increase the probability of 10 to as much as thrice of others and see the results:

for _ in range(5):
   print('Randomly picked number=>',random.choices(a,weights=[1,1,1,3,1,1],k=3))
random numbers python

Here, we can see that 10 occurred in every draw from the list. There also exists a sample() function in the random module that works similarly to the choices() function but takes random samples from a list without replacement.

Shuffling a List

Let’s say we don’t want to pick values from a list but you just want to reorder them. We can do this using the shuffle() function from the random module. This shuffle() function takes the list as an argument and shuffles the list in-place:

print('Original list=>',a)
random.shuffle(a)
print('Shuffled list=>',a)
Shuffling a List: random numbers python

Note: The shuffle() function does not return a list.

Generating Random Numbers According to Distributions

One more amazing feature of the random module is that it allows us to generate random numbers based on different probability distributions. There are various functions like gauss(), expovariate(), etc. which help us in doing this.

If you are not familiar with probability distributions, then I highly recommend you to read this article: 6 Common Probability Distributions every data science professional should know.

gauss()

Let’s start with the most common probability distribution, i.e., normal distribution. gauss() is a function of the random module used for generating random numbers according to a normal distribution. It takes mean and standard deviation as an argument and returns a random number:

for _ in range(5):
   print(random.gauss(0,1))
gauss()
gauss(): random numbers python

Here, I plotted 1000 random numbers generated by the gauss() function for mean equal to 0 and standard deviation as 1. You can see above that all the points are spread around the mean and they are not widely spread since the standard deviation is 1.

expovariate()

Exponential distribution is another very common probability distribution that you’ll encounter. The expovariate() function is used for getting a random number according to the exponential distribution. It takes the value of lambda as an argument and returns a value from 0 to positive infinity if lambda is positive, and from negative infinity to 0 if lambda is negative:

print('Random number from exponential distribution=>',random.expovariate(10))
Output: random numbers python

Conclusion

The production of random numbers using Python is easy and necessitate when it comes to computation and use in things like games. The random module offers a vast of possibilities for generating random integers, floating numbers and randomly selecting an element of the list. Cognition of how to seed random number generators as well as how to apply various forms of random number generation will be beneficial when programming to create vivid applications.

Key Takeaways

  • The random module in Python is essential for generating random numbers and selections.
  • Functions like randint(), uniform(), and choice() simplify the process of creating random values.
  • Seeding allows for reproducible random sequences, which can be useful for testing and debugging.

Frequently Asked Questions

Q1. What is the difference between choice() and choices()?

A. choice() returns a single random element from a list, while choices() can return multiple elements with replacement.

Q2. Can I generate random numbers for security purposes using the random module?

A. No, for security-sensitive applications, use the secrets module instead, which provides a secure random number generator.

Q3. How can I ensure that random numbers generated are reproducible?

A. By seeding the random number generator with a fixed value using random.seed(value), you can produce the same sequence of random numbers every time.

He is a data science aficionado, who loves diving into data and generating insights from it. He is always ready for making machines to learn through code and writing technical blogs. His areas of interest include Machine Learning and Natural Language Processing still open for something new and exciting.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details