\"
UncategorizedHow to Generate Random Numbers in Python: The ULTIMATE Guide for Beginners...

How to Generate Random Numbers in Python: The ULTIMATE Guide for Beginners and Experts

Random number generation is one of the most important things you’ll do in programming, from simulating data to Monte Carlo simulations, building games, or generating cryptographic keys. Python, with its rich ecosystem of libraries, provides a variety of ways to generate random numbers, each with different levels of randomness and use cases.

In this newly updated guide, we will see the most modern and efficient ways to generate random numbers in Python along with how to handle both simple random numbers and cryptographically secure numbers for sensitive applications.

1. Basics: Using random for simple random numbers

Python’s built-in random module is the first place to look when generating random numbers for simulations or other non-security-critical applications. This module offers a range of functions for generating random numbers and for random sampling.

Random Integer Generation

You can use the randint() function to generate random integers within a specified range.

import random

# Generate a random integer between 1 and 100
random_number = random.randint(1, 100)
print(random_number)

This will generate a random number between 1 and 100, inclusive.

Generating a Random Float

If you need a random floating-point number between 0 and 1, the random() function comes in handy:

import random
# Generate a random float between 0 and 1
random_float = random.random()
print(random_float)

You can scale this to any range you want, for example, a number between 1 and 100.

import random
# Random float between 1 and 100
random_float_range = random.uniform(1, 100)
print(random_float_range)

Shuffling a List

If you need to shuffle a list of items (such as selecting random elements), shuffle() is your friend:

import random
# Shuffle a list
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)

Sampling from a List

If you want to select multiple unique items from a list without replacement, use sample():

import random
# Define the list
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Get 3 unique random elements from the list
random_sample = random.sample(items, 3)
# Print the random sample
print(random_sample)

2. Data Science Randomness: Working with numpy

In data science and machine learning, generating random numbers often needs to be more performant and flexible. The numpy library is one of the most popular libraries used in data science that provides an optimized set of tools for random number generation.

Random Integers with numpy

For random integers generation in numpy, you can use numpy.random.randint().
import numpy as np

import numpy as np
# Generate 5 random integers between 1 and 100 (inclusive)
random_integers = np.random.randint(1, 101, size=5)
# Print the random integers
print(random_integers)

Random Floats with numpy

To generate random floats between 0 and 1, numpy offers numpy.random.rand():

import numpy as np
# Generate 5 random floats between 0 and 1
random_floats = np.random.rand(5)
# Print the random floats
print(random_floats)

You can also generate random floats within a specific range by scaling the output:

import numpy as np
# Generate 5 random floats between 1 and 100
random_float_range = np.random.uniform(1, 100, 5)
# Print the random floats
print(random_float_range)

3. Cryptographically Secure Random Numbers: Using secrets

For applications involving security-sensitive operations such as generating passwords or cryptography, one should use a cryptographically secure random number generator. Python’s secrets module has been provided since Python 3.6, which accesses a secure random number generator for use with security-critical applications.

Generating Secure Random Integers

You can generate cryptographically secure random integers using secrets.randbelow():

import secrets

import secrets
# Generate a secure random integer below 100
secure_random_int = secrets.randbelow(100)
# Print the secure random integer
print(secure_random_int)

Secure Random Bytes

For generating random bytes (which can be useful for generating random passwords or cryptographic keys), secrets.token_bytes() is a good choice:

import secrets
# Generate 16 random bytes
secure_random_bytes = secrets.token_bytes(16)
# Print the secure random bytes
print(secure_random_bytes)

This method is much more secure than using random or numpy for cryptographic purposes.

Secure Random String (e.g., Passwords)

If you’re building a system where you need to generate secure random passwords, you can use secrets to create a string with letters and digits:

import secrets
# Generate a secure random password (URL-safe base64-encoded string)
secure_password = secrets.token_urlsafe(16)
# Print the secure random password
print(secure_password)

This generates a random, URL-safe base64-encoded string, perfect for use as a password or token.

4. Best Practices for Random Number Generation

Choosing the Right Method

For non-security-critical applications: the random module is good and easy to use.
For data science tasks: numpy is extremely efficient and scalable when you have to generate large datasets of random numbers quickly.

For security applications: always use the secrets module, since it’s designed for cryptographically secure random numbers.

Seeding the Random Number Generator

In some scripts, you might want to be in control of the randomness, particularly while debugging or running experiments where you’d like the results to repeat. Both random and numpy allow the seeding of the random number generator to yield predictable results.

import random
# Seed the random number generator
random.seed(123)
# Generate a random integer between 1 and 100 (inclusive)
print(random.randint(1, 100))  # Will always generate the same result



Similarly,
numpy allows seeding:

import numpy as np
# Seed the random number generator for numpy
np.random.seed(123)
# Generate 5 random integers between 1 and 100 (inclusive)
print(np.random.randint(1, 100, 5))  # Will always generate the same result

5. Use Cases for Random Numbers in Python

  • Simulations: Monte Carlo simulations or random walks.
  • Games: Generating random levels, enemy positions, or loot drops.
  • Cryptography: Secure key generation, password creation, and token validation.
  • Data Science: Random sampling, bootstrapping, and generating synthetic datasets.

Conclusion

Generating random numbers is an essential task in many Python applications, from simple scripts to complex simulations and security systems. As of 2025, Python continues to provide a variety of libraries and methods to generate random numbers tailored to different needs.

  • For everyday tasks, the random module remains simple and effective.
  • For data science, numpy offers powerful tools for working with random numbers in arrays.
  • For cryptographic purposes, the secrets module ensures that random numbers are secure and suitable for sensitive applications.

Choose the method that best fits your needs, and always ensure you are using the right tool for the job—whether it’s for fast simulations, secure passwords, or large-scale data generation.

Now that you know how to generate random numbers in Python, explore these methods in your projects. Whether you’re simulating data or building secure systems, Python has you covered! If you have any questions or want to share your use cases, feel free to leave a comment below or subscribe for more Python tutorials.

 

 

 

 

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -