How to Randomly Generate Numbers in Python

How-to basics · Updated November 22, 2026

Random number generation is a core task in Python for simulations, games, sampling, cryptography, and testing. The standard library’s random module provides fast, reproducible pseudo-random numbers, while secrets is for cryptographically secure values. This guide shows you how to generate random integers, floats, and choices from a list, with clear examples and common pitfalls.

What You’ll Need

  • Python 3.6 or later installed (check with python --version).
  • A text editor or IDE (VS Code, PyCharm, or even IDLE).
  • No extra packages needed—everything uses the standard library.

Step-by-Step

  1. Import the random module. At the top of your script, add import random. This gives you access to all the pseudo-random functions.
  2. Generate a random integer between two values (inclusive). Use random.randint(a, b). For example, random.randint(1, 10) returns a whole number from 1 to 10. To get a number in a range with a step (like even numbers), use random.randrange(start, stop, step)—note that stop is exclusive. Example: random.randrange(0, 101, 5) gives multiples of 5 from 0 to 100.
  3. Generate a random float between 0 and 1. Call random.random(). It returns a float in [0.0, 1.0). To get a float in a custom range, multiply and add: random.random() * (max - min) + min. For a uniform float between two endpoints, use random.uniform(a, b) which includes both endpoints.
  4. Pick a random element from a list. Use random.choice(sequence). For example, random.choice(['red', 'green', 'blue']) returns one of those strings. To get multiple unique items, use random.sample(sequence, k) where k is the number of items. If you want duplicates allowed, use random.choices(sequence, k=n).
  5. Shuffle a list in place. Call random.shuffle(my_list). This modifies the original list. If you need a new shuffled copy, use random.sample(my_list, len(my_list)).
  6. Set a seed for reproducibility. Call random.seed(42) before generating numbers. This makes the sequence of random numbers identical every time you run the script, which is useful for debugging or tests.
  7. Use the secrets module for security-sensitive tasks. For passwords, tokens, or anything where predictability is a risk, import secrets instead. Use secrets.randbelow(n) for an integer from 0 to n-1, secrets.choice(sequence) for a secure choice, and secrets.token_hex(16) for a random hex string.
  8. Generate a random boolean. There’s no direct function, but you can use random.choice([True, False]) or random.random() < 0.5.
  9. Create a list of random numbers. Use a list comprehension: [random.randint(1, 100) for _ in range(10)] gives 10 integers from 1 to 100. For floats, use [random.uniform(0, 1) for _ in range(5)].
  10. Save and run your script. Save the file with a .py extension and run it from the terminal with python your_script.py.

Common Mistakes

  • Using random.randint for floats. It only returns integers. For floats, use random.uniform or random.random().
  • Forgetting that randrange excludes the stop value. random.randrange(1, 5) gives 1,2,3,4 but never 5.
  • Modifying a list while iterating over it. If you shuffle a list and then try to iterate and remove items, you may get unexpected results. Copy the list first if needed.
  • Using random for passwords. The random module is not cryptographically secure; an attacker could predict the sequence. Always use secrets for security.
  • Calling random.seed() inside a loop. This resets the generator each iteration, producing the same number repeatedly. Set the seed once at the start.

Tips

  • Use random.choices with weights. To make some outcomes more likely, pass a weights parameter: random.choices(['a','b'], weights=[1, 9], k=10) will return 'b' about 90% of the time.
  • For reproducible simulations, always set a seed. This lets you compare results across runs.
  • Use random.SystemRandom() if you need secure randomness but prefer the random API. It uses OS-provided entropy.
  • For large-scale random sampling, consider NumPy's numpy.random. It's faster and offers more distributions, but requires installing NumPy.
  • Test your random functions with a seed. This makes your tests deterministic.

Troubleshooting

  • I get the same number every time. You probably called random.seed() inside a loop or used a fixed seed intentionally. Remove the seed call or move it outside the loop.
  • I get an error like 'module' object has no attribute 'randint'. Make sure you didn't name your script random.py. That shadows the standard module. Rename your file.
  • I get a ValueError when using random.sample. The sample size k cannot be larger than the sequence length. Use random.choices if you need more items than the list has.
  • My random numbers are not truly random. The random module uses a deterministic algorithm, so it's pseudo-random. For cryptographic security, use secrets.
  • I want a random float but random.uniform returns the same value repeatedly. That might be because you set a seed and the same sequence is generated. Change the seed or remove it.

Frequently Asked Questions

  • What is the difference between random.randint and random.randrange? randint(a, b) includes both endpoints, while randrange(start, stop) excludes the stop value. randrange also supports a step argument.
  • How do I generate a random number from a normal distribution? Use random.gauss(mu, sigma) or random.normalvariate(mu, sigma). For other distributions, see the random module docs.
  • Can I generate random numbers without importing any module? No, you need the random module (or secrets). Python doesn't have built-in random functions without an import.
  • Is random thread-safe? The random module functions are not guaranteed thread-safe. If you use multiple threads, create separate random.Random() instances for each thread.
  • How do I generate a random date? Combine random.randint with datetime: pick a random day number and use datetime.date(year, month, day). For example, datetime.date(2025, random.randint(1,12), random.randint(1,28)).
  • Why is random.seed() useful? It makes the random sequence reproducible, which is essential for debugging, testing, and sharing results that can be replicated.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.