To generate random numbers in Python, use the random module from the standard library for most purposes (e.g., random.random(), random.randint(), random.choice()), or the secrets module when you need cryptographically secure randomness (e.g., passwords, tokens). For scientific computing, use numpy.random. This article explains each approach, how they work under the hood, and when to choose one over the other.
Background: Why Python Has Multiple Random Modules
Python’s standard library includes random since version 1.5 (1998), designed for simulations, games, and sampling. It uses the Mersenne Twister algorithm, which is fast and has a very long period (2^19937-1), but it is not suitable for security or cryptography because its state can be predicted if enough outputs are observed. The secrets module was added in Python 3.6 to address that gap, using the operating system’s cryptographically secure random number generator (CSPRNG). Meanwhile, numpy.random provides vectorized operations for large arrays, essential for data science and machine learning workflows.
How the random Module Works
The random module uses a pseudorandom number generator (PRNG) that starts from a seed value. If you set the seed with random.seed(42), you get the same sequence of numbers every time, which is useful for reproducible experiments. The core function random.random() returns a float in [0.0, 1.0). Other functions derive from it:
random.randint(a, b)– integer between a and b inclusive.random.uniform(a, b)– float in [a, b).random.choice(seq)– random element from a non-empty sequence.random.sample(pop, k)– k unique elements without replacement.random.shuffle(lst)– in-place shuffle of a list.
Example: import random; print(random.randint(1, 6)) simulates a die roll. The Mersenne Twister is deterministic, so without a seed, Python seeds it from system entropy (e.g., time, OS random) at import time.
Choosing Between random, secrets, and numpy.random
Your choice depends on three factors: security, performance, and reproducibility.
- Security: If the numbers are used for passwords, tokens, or anything that must be unpredictable to an attacker, use
secrets. For example,secrets.token_hex(16)generates a 32-character hex string. - Performance: For generating millions of numbers,
numpy.randomis much faster because it operates on arrays in C.randomis fine for a few thousand. - Reproducibility: Both
randomandnumpy.randomallow seeding.secretsdoes not allow seeding by design.
For most everyday scripting, random is the simplest. For scientific work, use numpy.random (e.g., np.random.normal(0, 1, 1000) for 1000 standard normal samples).
Cryptographically Secure Randomness with secrets
The secrets module is the only standard-library option that guarantees security. It uses os.urandom(), which on Windows and Linux draws from the system’s CSPRNG (e.g., CryptGenRandom or getrandom). Key functions:
secrets.randbelow(n)– random integer in [0, n).secrets.choice(seq)– secure random choice.secrets.token_bytes(n),token_hex(n),token_urlsafe(n)– generate random byte strings.
Example: import secrets; password = secrets.token_urlsafe(12) gives a 12-byte random URL-safe string. Never use random for generating API keys or session IDs; it is predictable.
Common Problems and Misconceptions
One frequent mistake is using random.random() to get an integer by multiplying, e.g., int(random.random() * 10) – this can produce 10 (out of range) due to floating-point rounding. Use randint(0, 9) instead. Another misconception is that random.shuffle() returns a new list – it shuffles in place and returns None. Also, many beginners think random.seed() makes numbers “more random” – it actually makes them deterministic. Finally, random.sample raises a ValueError if the sample size is larger than the population; use random.choices (with replacement) if you need duplicates.
Generating Random Numbers in Excel (for Context)
If you need random numbers in Excel, use =RAND() for a float between 0 and 1, =RANDBETWEEN(bottom, top) for integers, and =RANDARRAY(rows, cols) in Excel 365 to generate an array. These recalculate when the sheet changes. For reproducible results, you can set a seed by using a volatile function like =SEQUENCE(10) with a fixed seed in a helper column, but Excel does not have a direct seed function. For security, Excel is not appropriate; use a proper programming language.
Performance and Memory Considerations
Generating random numbers in pure Python is slow for large volumes. A list of 1 million floats with random.random() takes about 0.1 seconds, while numpy.random.random(1000000) takes about 0.005 seconds. Memory is also a factor: numpy arrays store data contiguously, whereas Python lists store pointers to objects. If you need to generate numbers on the fly without storing, consider a generator expression: (random.random() for _ in range(10**6)) – but it is still slower than numpy. For parallel processing, numpy.random has a default_rng() that supports independent streams.
Frequently Asked Questions
How do I generate a random integer between 1 and 100 in Python?
Use random.randint(1, 100). This returns an integer inclusive of both endpoints. If you need a float, use random.uniform(1, 100).
How do I make my random numbers reproducible?
Call random.seed(42) (or any integer) before generating numbers. For numpy, use np.random.seed(42) or create a generator with rng = np.random.default_rng(42). This is essential for debugging or sharing results.
What is the difference between random and secrets?
random is fast and reproducible but predictable; secrets is cryptographically secure and not reproducible. Use secrets for anything security-related, like password reset tokens or API keys.
Can I generate random numbers without importing any module?
No, Python does not have a built-in random function. You could use time.time() to get a float, but that is not truly random and is not recommended. Always use random or secrets.
How do I generate a random sample without replacement?
Use random.sample(population, k) where k is the number of items. It returns a new list of unique elements. For a large population, it is efficient because it uses a partial Fisher-Yates shuffle.
Why does random.random() sometimes return 1.0?
It does not. The documentation guarantees a float in [0.0, 1.0), meaning 1.0 is never included. If you see 1.0, it is likely due to rounding when printing or from a different function like uniform(0, 1) which is also exclusive of the upper bound.
Related
- Generate Random Number SAP? Explained
- Google Sheets PERCENTILE IF: Formula & Examples
- Shortcut for Saving in Excel: Ctrl+S and More
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Cell Counting Protocol: Step-by-Step GuideTo count cells accurately, use a hemocytometer (Neubauer chamber) with trypan blue exclusion: mix cells 1:1 with trypan…
- Excel Table in Word: Insert, Link, or Embed an Excel FileTo put Excel data in a Word document, select and copy the cells in Excel, then paste them…
- How to Mail Merge in Word 2010: A Step-by-Step GuideTo mail merge in Word 2010, open the Mailings tab, choose Start Mail Merge or Step-by-Step Mail Merge…
- Can You Consolidate Tabs in Excel? Methods ExplainedYes. In Excel for Microsoft 365, you can consolidate data from multiple worksheets with Data > Consolidate, or…
- How to Block Out and Share Your Outlook Calendar SafelyTo block out time in Outlook, create a calendar event for the period, set Show as to Busy…
- Control Shortcuts for Windows: Full List & How to Use ThemWindows keyboard shortcuts let you control windows (open, close, minimize, maximize, snap, switch) without touching the mouse. The…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.