1. Home
  2. Blog
  3. Software Development

Software Development

Python Random Module: randint, choice, seed and More

The Python random module generates random numbers, picks, samples and shuffles with no install. Learn the functions you will actually use, how seed makes results repeatable, how weights work, and why passwords and tokens need the secrets module instead, with tested output.

9 min read
Python random module: randint, choice, seed and more

Key takeaways

  • The Python random module is built in: import random and you are ready.
  • randint(a, b) includes both ends; randrange(a, b) excludes b.
  • random.seed(42) makes the sequence repeatable, which is ideal for tests and demos.
  • choices picks with replacement, sample picks without. shuffle changes the list in place and returns None.
  • Never use random for passwords or tokens. Use the secrets module.

Dice games, quiz apps, A/B test buckets, sample datasets, retry jitter: they all need randomness. The Python random module covers these jobs with a small set of functions, but a few details trip people up. Is the upper bound included? Why did shuffle return None? Why are my numbers the same on every run? And when is random not safe at all?

Every example below was run on Python 3.13.6. Where a seed is set, you will get exactly the same output on your machine, because the generator is deterministic. If you are just starting, our Python tutorial for beginners covers imports and lists first.

What is the Python random module?

random is a standard library module that produces pseudo-random numbers. They look random and pass statistical tests, but they come from a formula: the Mersenne Twister algorithm. Given the same starting state, called the seed, it produces the same sequence every time. That is a feature for simulations and tests, and a weakness for anything security related.

All the module-level functions share one hidden generator. When you call random.randint() and then random.choice(), both draw from the same stream, so the order of calls changes the results.

Random integers: randint and randrange

import random
random.seed(42)

print(random.random())                              # 0.6394267984578837
print([random.randint(1, 6) for _ in range(5)])     # [1, 6, 3, 2, 2]
print([random.randrange(0, 10, 2) for _ in range(5)])  # [2, 0, 8, 0, 8]

The difference matters:

  • randint(1, 6) returns 1 to 6 inclusive, perfect for a dice roll.
  • randrange(start, stop, step) follows range() rules, so stop is excluded. randrange(0, 10, 2) returns only even numbers from 0 to 8.

If you want a random index into a list of length n, randrange(n) is the natural fit, because it can never return n itself and cause an IndexError.

Random floats: random and uniform

random.random() returns a float in the half-open range [0.0, 1.0). For any other range, use uniform:

print(round(random.uniform(1.5, 2.5), 4))   # 1.9219

A common pattern is a probability check, such as if random.random() < 0.1: to run something about 10 percent of the time. Another is retry jitter: time.sleep(base * random.uniform(0.5, 1.5)) spreads retries so that many clients do not hit a recovering server at the same instant.

Picking items: choice and choices

colors = ["red", "green", "blue"]
print(random.choice(colors))        # red
print(random.choices(colors, k=5))  # ['red', 'red', 'green', 'green', 'blue']

choice returns one item. choices returns a list of k items with replacement, so the same item can appear more than once, as red and green did above. Calling choice on an empty list raises IndexError, so guard against empty input.

sample vs choices: with or without replacement

print(random.sample(range(1, 11), 3))   # [9, 7, 4]

random.sample(colors, 5)
# ValueError: Sample larger than population or is negative

sample picks unique positions, like drawing raffle tickets from a hat without putting them back. That is why asking for 5 items from a 3-item list fails, while choices(colors, k=5) works fine. Use sample for lottery numbers, picking winners or selecting test accounts; use choices for simulating repeated independent events.

Function Returns Repeats possible?
choice(seq) One item n/a
choices(seq, k=n) List of n Yes
sample(seq, n) List of n No
shuffle(list) None (in place) No

Shuffling a list

deck = list(range(1, 11))
random.shuffle(deck)
print(deck)                   # [9, 10, 6, 3, 4, 2, 7, 1, 5, 8]
print(random.shuffle(deck))   # None

shuffle rearranges the list itself and returns None. Writing deck = random.shuffle(deck) is a classic bug that leaves you with None. If you need a shuffled copy and want to keep the original, use random.sample(deck, len(deck)). Shuffle only works on mutable sequences, so convert a tuple or string to a list first.

random.seed: repeatable results

random.seed(42); a = [random.randint(1, 100) for _ in range(3)]
random.seed(42); b = [random.randint(1, 100) for _ in range(3)]
print(a, b, a == b)   # [82, 15, 4] [82, 15, 4] True

Setting a seed resets the generator to a known state, so the following calls repeat exactly. Use it in unit tests, data science notebooks, games with shareable level codes and any demo where readers should see your output. Without a seed, Python seeds itself from the operating system, so each run differs.

Tip: seed once at the start of a program or test, not before every call. Reseeding inside a loop with the same value returns the same number over and over.

Weighted random choices

Pass weights to make some outcomes more likely. We drew 100,000 times with a 90 to 10 weighting:

import collections
random.seed(7)
picks = random.choices(["common", "rare"], weights=[90, 10], k=100_000)
print(collections.Counter(picks))
# {'common': 90095, 'rare': 9905}

The result landed within 0.1 percent of the target. Weights do not need to sum to 100; [9, 1] gives the same odds. This is how you would build loot tables, traffic splits for an experiment or realistic fake data where most orders are small and a few are large. collections.Counter is covered in our Python collections guide.

Is Python random actually fair?

We rolled a virtual die 60,000 times with randint(1, 6). A fair die should land on each face about 10,000 times:

Face 1 2 3 4 5 6
Count 9,986 10,061 9,954 9,987 10,002 10,010

Every face is within 0.7 percent of 10,000, exactly the kind of small wobble you expect from real randomness. The Mersenne Twister has excellent statistical quality for games, simulations and sampling. Its weakness is predictability, not bias.

Other distributions: gauss and friends

Not all randomness is uniform. Heights, response times and measurement errors cluster around an average. random.gauss(mu, sigma) draws from a normal distribution:

import statistics
random.seed(1)
g = [random.gauss(170, 10) for _ in range(50_000)]
print(round(statistics.mean(g), 2), round(statistics.stdev(g), 2))
# 170.05 10.01

The sample mean and standard deviation came out almost exactly at the 170 and 10 we asked for. The module also offers expovariate for waiting times, triangular, betavariate and more, which are handy when you need realistic test data generation.

Independent generators with random.Random

Because module functions share one global state, a library that calls random can shift your sequence. Create your own generator object to isolate it:

r1 = random.Random(99)
r2 = random.Random(99)
print(r1.randint(1, 1000), r2.randint(1, 1000))   # 414 414

Each Random instance keeps its own state, so two instances with the same seed produce the same values no matter what other code does. This is the cleanest way to make a simulation reproducible inside a larger program.

random vs secrets: security matters

Because Mersenne Twister is deterministic, anyone who knows or recovers the state can predict future values. We showed this with a seeded “password”:

random.seed(3); pw1 = "".join(random.choice("abc123") for _ in range(8))
random.seed(3); pw2 = "".join(random.choice("abc123") for _ in range(8))
print(pw1 == pw2)   # True

For passwords, API keys, reset links and session tokens, use secrets, which draws from the operating system’s cryptographic source:

import secrets
print(len(secrets.token_hex(8)))   # 16  (8 random bytes as hex)
print(secrets.randbelow(10))       # 0 to 9, unpredictable

random.SystemRandom uses the same OS source. We seeded one twice with the same value and got different numbers each time, confirming that its seed has no effect.

How fast is random?

Call Time per call
random.random() 26.9 ns
random.randint(1, 6) 336.8 ns
secrets.randbelow(6) 575.3 ns

Best of three runs of 200,000 calls each. randint is about 12 times slower than random() because of argument checks and rejection sampling, but even a million calls take only a third of a second. secrets is slower again, yet still far too fast to matter for generating a token.

Using random in tests

  • Seed the generator in a pytest fixture so failures can be reproduced.
  • Print or log the seed when a randomized test fails, so you can rerun the exact case.
  • Pass a random.Random instance into your code instead of calling the module directly; tests can then inject a seeded one.
  • For deeper randomized testing, try property-based testing, which generates and shrinks inputs for you.

Python random cheat sheet

Need Use
Float 0 to 1 random.random()
Integer a to b inclusive random.randint(a, b)
Random index random.randrange(len(seq))
One item random.choice(seq)
Unique items random.sample(seq, k)
Weighted picks random.choices(seq, weights=w, k=n)
Shuffle in place random.shuffle(lst)
Repeatable run random.seed(42)
Token or password secrets.token_urlsafe()

Final thoughts

The Python random module is small but covers almost every everyday need: integers, floats, picks, samples, shuffles and weighted draws. Remember that randint includes both ends, that shuffle returns None, and that a seed makes results repeatable. Keep random for games, simulations and tests, and switch to secrets the moment security is involved.

Frequently asked questions

Is randint inclusive in Python?

Yes. random.randint(a, b) can return both a and b. If you want the upper bound excluded, use random.randrange(a, b) instead.

How do I get the same random numbers every time?

Call random.seed with a fixed value, such as random.seed(42), before generating numbers. The same seed always produces the same sequence on the same Python version.

Why does random.shuffle return None?

shuffle changes the list in place and returns None by design. Shuffle the list on its own line, or use random.sample(items, len(items)) to get a shuffled copy.

What is the difference between choice and choices?

choice returns a single item. choices returns a list of k items picked with replacement and accepts weights, so the same item can appear more than once.

Is Python random safe for passwords?

No. The random module is predictable once its state is known. Use the secrets module, for example secrets.token_urlsafe or secrets.choice, for passwords, tokens and keys.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Software Development

Python Random Module: randint, choice, seed and More

The Python random module explained: randint, randrange, choice, choices, sample, shuffle, seed, weights and when to use secrets instead, with…

Read article →
Software Development

Python Slicing Explained: Start, Stop and Step With Examples

Python slicing explained with start, stop and step, negative indexes, reversing, copying and slice assignment, with tested examples and a…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →