Generate Random Unique Number in Python

Formulas & functions · Updated November 23, 2026

To generate a random unique number in Python, use the random.randint() function for a single random integer, or random.sample() to get a list of unique numbers from a range without repetition. For example, random.randint(1, 100) returns one random integer between 1 and 100, while random.sample(range(1, 101), 5) returns 5 unique numbers from that range.

Why Uniqueness Matters in Random Generation

Random numbers are used everywhere: simulations, games, cryptography, statistical sampling, and even assigning IDs. The challenge is that “random” and “unique” are two different properties. A random number can repeat by chance; uniqueness means no value appears more than once in a given set. For example, rolling a die 6 times could give you 3, 5, 3, 1, 6, 2 – the 3 repeats. If you need each number to appear only once (like shuffling a deck), you must explicitly enforce uniqueness.

Python’s standard library gives you several tools, but none of them generate a “unique random number” directly. Instead, you combine a random generator with a method that prevents duplicates. The correct approach depends on whether you need one number, a fixed set, or a sequence that never repeats.

Using random.randint() for a Single Number

The simplest way to get one random integer is random.randint(a, b). It returns a random integer N such that a <= N <= b. For example:

import random
print(random.randint(1, 10))  # Output could be any integer from 1 to 10

This is not unique by itself – if you call it twice, you might get the same number. To guarantee uniqueness across multiple calls, you need to track what has been used. A common pattern is to use a set to store already generated numbers and loop until you find a new one:

import random
used = set()
def unique_randint(a, b):
    while True:
        n = random.randint(a, b)
        if n not in used:
            used.add(n)
            return n

Be careful: if you request more unique numbers than the range size (b - a + 1), this loop will run forever. Always check that the range is large enough.

Generating a List of Unique Numbers with random.sample()

If you need several unique numbers at once, random.sample(population, k) is the cleanest solution. It returns a list of k unique elements chosen from the population sequence. For example:

import random
unique_numbers = random.sample(range(1, 101), 5)
print(unique_numbers)  # e.g., [42, 17, 89, 3, 56]

This works without replacement, meaning no duplicates. The population can be any sequence, but range() is memory-efficient for large ranges because it doesn’t create a list in memory. If you need numbers from a non-contiguous set, pass a list or tuple.

Important: random.sample() raises a ValueError if k is larger than the population size. For example, random.sample(range(1, 4), 5) fails because you can’t pick 5 unique numbers from only 3 possible values.

Shuffling a Range with random.shuffle()

Another way to get a set of unique numbers is to create a list of all possible numbers, shuffle it, and then take the first few. This is equivalent to random.sample() but gives you more control if you need to process the entire sequence in a random order (like a lottery draw). Example:

import random
numbers = list(range(1, 101))
random.shuffle(numbers)
unique_numbers = numbers[:5]  # first 5 after shuffle

This modifies the original list in place. It’s useful when you need to consume the numbers one by one without repetition, but it uses memory proportional to the range size. For huge ranges (millions), random.sample() is more efficient because it doesn’t create the full list.

Secrets Module for Cryptographically Secure Numbers

If you need random numbers for security purposes (passwords, tokens, encryption), the random module is not suitable because its output is predictable. Instead, use the secrets module, designed for cryptographically strong randomness. For a unique secure integer:

import secrets
secure_number = secrets.randbelow(100) + 1  # random integer from 1 to 100

For a unique secure token (hex string):

import secrets
token = secrets.token_hex(16)  # 32-character hex string

To get a list of unique secure numbers, combine secrets.randbelow() with a set, similar to the earlier pattern. The secrets module is slower than random, so use it only when security is critical.

Common Pitfalls and How to Avoid Them

  • Forgetting that random.randint() can repeat: If you call it in a loop without checking, you may get duplicates. Always use a set or random.sample().
  • Using random.random() for integers: random.random() returns a float between 0 and 1, not an integer. Convert with int() if needed, but be aware of rounding.
  • Running out of unique numbers: If you try to generate more unique numbers than the range allows, you’ll get an error or infinite loop. Check the range size first.
  • Using random.seed() unintentionally: Seeding makes the sequence reproducible, which is good for testing but not for true randomness. Don’t seed unless you need repeatable results.
  • Not importing the module: A common beginner mistake is forgetting import random at the top of the file.

Comparing random, numpy, and secrets

Python’s built-in random is fine for most non-security tasks. However, if you’re working with large arrays or need many random numbers quickly, the numpy library offers numpy.random.randint() and numpy.random.choice() with replace=False for uniqueness. Example:

import numpy as np
unique_numbers = np.random.choice(np.arange(1, 101), size=5, replace=False)

This is faster for large samples, but numpy is a third-party library that must be installed. For security, secrets is the only correct choice. In short:

  • random – general purpose, fast, not secure.
  • numpy.random – fast for arrays, not secure.
  • secrets – secure, slower.

Generating Unique Numbers Without Repetition Over Time

Sometimes you need a stream of unique numbers across multiple program runs (e.g., generating unique IDs for a database). In that case, you cannot rely on randomness alone because you might generate the same number later. Instead, use a counter or a timestamp combined with randomness. For example:

import time
import random
unique_id = f"{int(time.time())}-{random.randint(1000, 9999)}"

This combines the current Unix timestamp with a random suffix, making collisions extremely unlikely. For truly guaranteed uniqueness, use a database auto-increment or a UUID (universally unique identifier) via uuid.uuid4():

import uuid
unique_id = uuid.uuid4()  # e.g., 123e4567-e89b-12d3-a456-426614174000

UUIDs are not random numbers in the integer sense, but they are unique across space and time, which is often what people actually need.

Frequently Asked Questions

How do I generate a random unique number in Python without repetition?

Use random.sample(range(start, end+1), k) to get a list of k unique numbers. For example, random.sample(range(1, 101), 10) gives 10 unique integers from 1 to 100. If you need to generate them one at a time, maintain a set of used numbers and loop with random.randint() until you find a new one.

What is the difference between random.randint() and random.randrange()?

random.randint(a, b) includes both endpoints, so it can return b. random.randrange(a, b) excludes b, like range(). For example, random.randint(1, 10) can return 10, but random.randrange(1, 10) only returns 1 to 9. Use randrange when you want a range that matches Python’s zero-based indexing.

Can I generate a random unique number in a specific range without using a list?

Yes, for a single number you can use random.randint() and store the result in a set. For multiple numbers, random.sample() is the most direct, but it internally uses a list for the population. If you have a huge range, random.sample() with a range object is memory-efficient because it doesn’t create the full list.

Is random.sample() truly random?

Yes, it uses the same pseudo-random number generator as random.randint(). The selection is uniform, meaning each element has an equal chance of being chosen, and it does so without replacement. However, it is not cryptographically secure; for security, use secrets.

How do I generate a random unique number in Python 3?

The same functions work in Python 3. Just import random and use random.randint() or random.sample(). The secrets module is also available in Python 3.6 and later. There is no difference in syntax between Python 2 and 3 for these basic functions, but Python 2 is deprecated.

What is the best way to generate a unique random number for a primary key?

For a database primary key, don’t rely on randomness; use an auto-increment integer or a UUID. If you must use a random number, use secrets.randbelow() to make it unpredictable, and check for collisions in the database. A UUID is simpler and guarantees uniqueness without a central counter.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.