Generate random integers between 0 and 9
To generate a random integer from 0 to 9 inclusive, use the random.randint(0, 9)
function from the random
module:
Need a list of random numbers? Python makes it super easy with list comprehension:
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 integerN
betweena
andb
inclusive.
For those VIPs who need extra security, Python's secrets
module offers cryptographically secure randomness:
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:
No two numbers alike:
For a unique list of random numbers; random.sample()
has you covered:
Repeat Performance:
To create the same "random" sequence; you can seed your generator:
Was this article helpful?