Choose random items from a Python list

Use choice, sample, choices, and shuffle correctly, including duplicate values, weighted draws, reproducible tests, and security-sensitive selection.

Best practices
Python programming and application logging

Use random.choice(items) to select one element from a nonempty sequence. Use random.sample(items, count) to draw without replacement, or random.choices(items, k=count) to allow replacement.

Select one item

import random

items = ["apple", "banana", "cherry", "date"]
selected = random.choice(items)
print(selected)

An empty sequence raises IndexError. Decide whether an empty input should be an error or should return an application-specific default. Tuples and strings also work; a string selection returns one code point.

Draw several items

chosen = random.sample(items, 2)
print(chosen)

sample returns a new list and leaves the input alone. It selects distinct positions, not necessarily distinct values: sampling both entries from ["apple", "apple"] returns two equal values. Asking for more positions than exist, or a negative count, raises ValueError.

If your requirement is unique values, deduplicate the population deliberately first. That changes the probabilities when duplicates previously represented frequency.

Shuffle or weight the selection

shuffled = items.copy()
random.shuffle(shuffled)
print(shuffled)

selected = random.choices(
    items, weights=[0.7, 0.2, 0.05, 0.05], k=1
)[0]

shuffle changes its list in place and returns None. Here it operates on a copy, preserving the original order so the weights still correspond to apple, banana, cherry, and date. The weights are relative, must match the population length, and should be finite, nonnegative, and not all zero. Repeated weighted draws can select the same position more than once.

Choose the appropriate random source

For security-sensitive choices, use secrets.choice(items). The ordinary random generator is deterministic and is unsuitable for credentials or authentication tokens.

For a reproducible test, create an isolated generator:

rng = random.Random(42)
print(rng.choice(items))

Pin the Python version and sequence of calls when exact outcomes matter; do not assume every high-level random operation has identical output across versions.

FAQ

How do I sample a NumPy array? A NumPy generator, created with numpy.random.default_rng(), provides choice with replace and p options. Match its shape and probability requirements to your array.

Does a fixed seed make a secure token? No. A predictable sequence defeats the purpose of a secret. Use secrets and an adequate token length instead.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting