How to create Random Numbers in Python

Najma Bader
2 min readApr 5, 2022

--

Photo By Riho Kroll

Random numbers (or better pseudo-random numbers) can be very useful in Python, especially if you want to test your code.

Fortunately, this can be easily achieved using the built-in module random There are a lot of methods defined for this module, and you can read more about it on the official documentation or on the w3school website.

The ones I have used the most are:

  • random.random() → returns a random floating number between 0 and 1.
  • random.uniform() → returns a random floating number between the two specified numbers (both included).
  • random.randint() → returns a random integer number selected element from a range (both included).

Examples

If you instead want to create a list of pseudo-random numbers, you can use the sample() method which returns a random selection from a sequence. You specify how many items you want by using the parameter k :

This method can be used to create a random list of integers:

Or a random list of floats:

What if you want to make your output reproducible?

You can use the seed() method to initialize the random number generator.
In this way, the random number generator will always “start” from the same number and no matter how many times you run your program you will get the same results:

I hope this helped! ⚡️

References

--

--

Najma Bader

I grew up in a hippie family but I fell in love with coding. I write about my experience with Python, Big Data and other nice things ❤️