Explain Codes LogoExplain Codes Logo

Generate random integers between 0 and 9

python
random-number-generation
pseudo-random-number-generator
python-module
Nikita BarsukovbyNikita Barsukov·Sep 5, 2024
TLDR

To generate a random integer from 0 to 9 inclusive, use the random.randint(0, 9) function from the random module:

from random import randint print(randint(0, 9)) # Prints a random integer from [0, 9] and hopefully your lucky number!

Need a list of random numbers? Python makes it super easy with list comprehension:

random_numbers = [randint(0, 9) for _ in range(10)] print(random_numbers) # List of 10 random integers for your very own random lottery!

Digging into the random module

Pseudo-random number generator (PRNG) is the man behind the curtain for the random module in Python. It's not perfect, but works well for most randomization operations, especially if you remember to tip your PRNG dealer with a seed.

Functions you'll meet at the random casino:

  • randrange(stop): Spins the wheel and picks a number from 0 up to (stop-1).
  • randint(a, b): Rolls the dice for a random integer N between a and b inclusive.

For those VIPs who need extra security, Python's secrets module offers cryptographically secure randomness:

import secrets secure_num = secrets.randbelow(10) # Rolls a secure dice that can't be rigged!

Pro tip: Use secrets for your mission-critical, enemy-evading cryptographic needs. It may be slower, but it has your back even under the harshest scrutiny.

Advanced usage tips and gotchas

Python makes working with random numbers a breeze, but remember these tips to avoid common pitfalls:

  • Floats need not apply uniform() is great if you like to play with decimals. But if you strictly need an integer, find another game.
  • Looking for unique random numbers? Use random.sample(range(0, 10), number_of_unique_values) to ensure you have a house of different cards.
  • Need to reproduce results? Set your PRNG seed with random.seed().
  • Running a speed race? Remember, random is like the hare: quick but less secure. secrets is the tortoise: slower but steady and secure.

Hey, you've just leveled up your knowledge of random number generation!

Generating sequences and special cases

Need more than one number? Want to control the randomness? Here are more tricks up Python's sleeve.

Multiple random integers with a twist:

For generating a sequence of random integers, Python gives you the power of generator expressions:

random_generator = (randint(0, 9) for _ in range(1000)) # Create your own number stream!

No two numbers alike:

For a unique list of random numbers; random.sample() has you covered:

unique_randoms = random.sample(range(10), 5) # No number will feel left out.

Repeat Performance:

To create the same "random" sequence; you can seed your generator:

random.seed(42) predictable_output = [randint(0, 9) for _ in range(5)] # For when you hate surprises.