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
- Import the random module. At the top of your script, add
import random. This gives you access to all the pseudo-random functions. - 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), userandom.randrange(start, stop, step)—note thatstopis exclusive. Example:random.randrange(0, 101, 5)gives multiples of 5 from 0 to 100. - 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, userandom.uniform(a, b)which includes both endpoints. - 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, userandom.sample(sequence, k)wherekis the number of items. If you want duplicates allowed, userandom.choices(sequence, k=n). - Shuffle a list in place. Call
random.shuffle(my_list). This modifies the original list. If you need a new shuffled copy, userandom.sample(my_list, len(my_list)). - 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. - Use the secrets module for security-sensitive tasks. For passwords, tokens, or anything where predictability is a risk, import
secretsinstead. Usesecrets.randbelow(n)for an integer from 0 to n-1,secrets.choice(sequence)for a secure choice, andsecrets.token_hex(16)for a random hex string. - Generate a random boolean. There’s no direct function, but you can use
random.choice([True, False])orrandom.random() < 0.5. - 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)]. - Save and run your script. Save the file with a
.pyextension and run it from the terminal withpython your_script.py.
Common Mistakes
- Using
random.randintfor floats. It only returns integers. For floats, userandom.uniformorrandom.random(). - Forgetting that
randrangeexcludes 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
randomfor passwords. Therandommodule is not cryptographically secure; an attacker could predict the sequence. Always usesecretsfor 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.choiceswith weights. To make some outcomes more likely, pass aweightsparameter: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 therandomAPI. 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 sizekcannot be larger than the sequence length. Userandom.choicesif you need more items than the list has. - My random numbers are not truly random. The
randommodule uses a deterministic algorithm, so it's pseudo-random. For cryptographic security, usesecrets. - I want a random float but
random.uniformreturns 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.randintandrandom.randrange?randint(a, b)includes both endpoints, whilerandrange(start, stop)excludes the stop value.randrangealso supports a step argument. - How do I generate a random number from a normal distribution? Use
random.gauss(mu, sigma)orrandom.normalvariate(mu, sigma). For other distributions, see therandommodule docs. - Can I generate random numbers without importing any module? No, you need the
randommodule (orsecrets). Python doesn't have built-in random functions without an import. - Is
randomthread-safe? Therandommodule functions are not guaranteed thread-safe. If you use multiple threads, create separaterandom.Random()instances for each thread. - How do I generate a random date? Combine
random.randintwithdatetime: pick a random day number and usedatetime.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
- How to Create an Enum in Java
- Computer Shortcuts Windows: The Essential List
- Ctrl Button Shortcuts: The Essential List
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Create a Reusable Stationery Template in WordTo create a reusable stationery template in Word, design the page, place recurring elements such as a logo…
- Creating a Cover Page in Word: Steps and Design TipsTo create a cover page in Microsoft Word, open the Insert tab, choose Cover Page in the Pages…
- Excel Spreadsheet for Contact Information: How to Build OneYes, you can use an Excel spreadsheet to store contact information, and it works well for personal address…
- How to Create Rules in Outlook 365 to Organize EmailTo create a rule in Outlook 365, open Settings > Mail > Rules in new Outlook or Outlook…
- Batch Archive Emails in Outlook: Step-by-Step GuideTo batch archive emails in Outlook, open the folder or search results containing the messages, select the messages…
- Snowflake LATERAL SPLIT_TO_TABLE: Syntax and ExamplesYes. In Snowflake, use LATERAL SPLIT_TO_TABLE in the FROM clause to turn a delimited string in each source…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.