Python random — seed, randint, choice, and shuffle
A program often needs a value it does not choose in advance: a die roll, a shuffled list, a sample from a larger set, or a test value drawn from a distribution. The random module makes those draws, and a seed makes the same draws come back in the same order, which turns a random test into a test that can fail and be run again. This guide takes the seed first, then floats, integers, picks, shuffles, samples, distributions, and the state and error cases.
Written November 13, 2026 · Tested with Python 3.12.3 · 10 min read
- The main program: seed and random
- Integers: randint, randrange, and getrandbits
- Picks: choice and choices
- Shuffle: reorder a list in place
Written November 13, 2026
Tested with Python 3.12.3
What this guide is
The random module draws pseudo-random values: floats, integers, picks from a sequence, shuffled orders, samples, and values from named distributions. The draws come from a generator with a state. Set the state at the start with seed, and the whole sequence that follows is fixed. Leave the seed unset, and the module seeds itself from the system time or from operating system sources, so the sequence differs from run to run. One limit matters before any code: these generators are built for modeling and simulation, not for security. Passwords, tokens, and anything an attacker should not be able to predict belong to the secrets module, not to this one.
The main program: seed and random
The random call returns a float from 0.0 up to, but not including, 1.0. The seed call restarts the sequence. Seed with the same value again, and the next draw is the same first value again. The uniform call returns a float between two endpoints, scaled from that same float draw:
import random
random.seed(42)
print(random.random())
print(random.random())
random.seed(42)
print(random.random())
print(round(random.uniform(1, 10), 6))
The exact output:
0.6394267984578837
0.025010755222666936
0.6394267984578837
1.225097
The first and third lines match because the seed reset the sequence between them. That match is the working tool in this module: a test, a simulation, or a generated data set that seeds itself at the start can be run again after a change and give the same draws, so a difference in the result comes from the change, not from the draw. Seed with a value that the job records, and the run can be repeated by anyone who has that value.
Integers: randint, randrange, and getrandbits
Three calls draw integers, and they differ in how the range is stated. The randint call includes both endpoints, so randint(1, 10) can return 1 and can return 10. The randrange call follows the range rule used across Python: the stop value is not included, and a step can be given. The getrandbits call returns an integer built from a stated number of random bits:
import random
random.seed(42)
print(random.randint(1, 10))
print(random.randint(1, 10))
print(random.randrange(0, 100, 10))
print(random.randrange(5))
print(random.getrandbits(8))
The exact output:
2
1
40
1
57
The third line can only be a multiple of 10 below 100, because the call gave a start of 0, a stop of 100, and a step of 10. The fourth line shows the one-argument form, which draws from 0 up to, but not including, 5. Pick randint when the job states its range the way people state a die or a number of sides. Pick randrange when the range already exists as a range in the code, because the two use the same start, stop, and step values with no adjustment at either end.
Picks: choice and choices
The choice call returns one item from a sequence. The choices call returns a list of k items, drawn with replacement, so the same item can appear more than once in the result. Weights can be given, one per item, and an item with a larger weight is drawn more often in proportion to that weight:
import random
random.seed(42)
items = ["red", "green", "blue", "yellow"]
print(random.choice(items))
print(random.choices(items, k=3))
print(random.choices(["win", "lose"], weights=[1, 9], k=5))
The exact output:
red
['red', 'green', 'red']
['lose', 'lose', 'lose', 'win', 'lose']
The second line holds the proof of replacement: red appears twice in a three-item pick from a list that holds it once. The third line shows the weight effect in a small sample: lose, with nine times the weight of win, takes four of the five places. A small sample can still run against the weights, so the weights state a proportion over many draws, not a count in any one result. Code that needs each item at most once should not use choices at all; it should use sample, in the next section but one.
Shuffle: reorder a list in place
The shuffle call reorders a list in place. It returns nothing, and the list passed in is the list that changes. Every order of the items is equally likely:
import random
random.seed(42)
cards = [1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(cards)
print(cards)
print(random.sample([10, 20, 30, 40, 50], k=3))
print(sorted(random.sample(range(100), k=5)))
The exact output:
[4, 5, 7, 8, 3, 6, 1, 2]
[10, 50, 30]
[3, 4, 11, 27, 54]
The last two lines use sample, which returns a new list and leaves its input alone. That difference in shape is the choice between the two calls. Use shuffle when the job owns the list and wants it reordered, such as a deck or a playlist. Use sample when the job needs a drawn subset and the source list must stay as it was. A common defect is to assign the result of shuffle to a variable and then use that variable: the result is None, and the shuffled list is the original one.
Sample: picks without repeats, and counts
The sample call draws k items from a population with no repeats in the result. The k value can be 0, which returns an empty list. A counts argument can be given beside the population: each count states how many copies of that item the population holds, so an item can appear in the result up to its count, and no further:
import random
random.seed(1)
print(random.sample(["a", "b", "c"], counts=[3, 2, 1], k=4))
random.seed(42)
print(random.sample(range(10), k=3))
print(random.sample(range(10), k=0))
The exact output:
['a', 'b', 'a', 'c']
[1, 0, 4]
[]
The first line holds a twice and c once, inside the counts of three and one that the call allowed. Without counts, no value repeats, as the second line shows. Counts are the form to use when the population is described by how many of each kind exist — three red, two blue, one green — and building the full repeated list by hand would be wasted work. The total of the counts is the real population size for the error rule in the last section: k cannot be larger than that total.
Distributions: gauss, triangular, exponential, and beta
Four distribution calls draw floats shaped by their parameters rather than flat across a range. The gauss call draws from a normal distribution with a mean and a standard deviation. The triangular call draws between a low and a high point, pulled toward a mode. The expovariate call draws waiting times for events that occur at a stated rate. The betavariate call draws a value between 0 and 1 shaped by two positive parameters:
import random
random.seed(42)
print(round(random.gauss(100, 15), 6))
print(round(random.triangular(0, 10, 3), 6))
print(round(random.expovariate(0.5), 6))
print(round(random.betavariate(2, 5), 6))
The exact output:
97.838645
2.872434
0.505172
0.44572
A single draw says little about a distribution; the shape shows over many draws. The gauss draw here sits near its mean of 100, as most gauss draws do, because the normal curve is tallest at the mean. The triangular draw sits below the middle of its range, pulled toward the mode of 3. These calls are the input side of a simulation: the parameters state what the job believes about the values, and the draws feed that belief through the rest of the program, where the results can be summed and compared with statistics summaries.
State, and the error cases
The getstate call returns the current state of the generator, and setstate puts a saved state back. Draw after restoring a state, and the draw is the same one that followed the save. Three error cases close the guide. A pick from an empty sequence raises IndexError. A sample larger than the population raises ValueError, and a weights list whose length does not match the population raises ValueError as well:
import random
random.seed(42)
state = random.getstate()
print(random.randint(1, 100))
random.setstate(state)
print(random.randint(1, 100))
try:
random.choice([])
except IndexError as e:
print(type(e).__name__)
try:
random.sample([1, 2], k=3)
except ValueError as e:
print(type(e).__name__)
try:
random.choices([1, 2], weights=[1], k=1)
except ValueError as e:
print(type(e).__name__)
The exact output:
82
82
IndexError
ValueError
ValueError
Saved state is the heavier form of the seed tool. A seed restarts a sequence from its start; a saved state restarts it from the middle, at the point the save was taken. Long simulations use it to resume without replaying every earlier draw. The error cases share one shape: each call states what it needs — a non-empty sequence for a pick, at least k items in the population for a sample, and one weight per item for a weighted pick — and code that builds its population from input should check those counts before the call, or catch the error and report the short input as the problem it is.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| Repeatable sequence | seed | Same draws in same order |
| Float in a range | uniform | Scaled between endpoints |
| Integer, both ends in | randint | Endpoints included |
| Integer from a range | randrange | Stop excluded, step allowed |
| One item | choice | Single pick |
| Picks with repeats | choices | Drawn with replacement |
| Reorder owned list | shuffle | Changes list in place |
| Picks, no repeats | sample | Each item at most once |
| Passwords and tokens | secrets module | Built for security use |
Checklist
- Seed at the start of any test, simulation, or generated data set that must be run again, and record the seed value with the job.
- Pick randint for a range stated with both ends in, and randrange for a range that already exists as a range.
- Use choices when repeats are allowed, and sample when each item may appear at most once.
- Remember that shuffle changes the list in place and returns None.
- Check the population size before a sample, and the weights length before a weighted pick.
- Keep passwords, tokens, and other secrets out of this module; use the secrets module for those.
Related guides on this site
- Python statistics — mean, median, mode, and spread — the summaries that describe a set of drawn values after a simulation runs.
- Python math — sqrt, floor, gcd, and log — the rounding used on the distribution draws in this guide.
- Python Lists, Dicts, and Sets — The Three Collections You Use Every Day — the lists that choice, shuffle, and sample work on.
- Python Functions — def, Default Arguments, and Functions as Values — the call forms every random call in this guide follows.
Sources
- Python Standard Library, random — seed, random, uniform, randint, randrange, getrandbits, choice, choices, shuffle, sample and its counts form, gauss, triangular, expovariate, betavariate, getstate and setstate, and the note that the generators are not suited to security use.
- Python Standard Library, secrets — the module for passwords, tokens, and other values that must resist prediction.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.