If you have 100 million numbers like in the question, then this is actually manageable in-memory (it takes about 0.5 GB).

As DSM pointed out, this can be done with the standard modules in an efficient way:

>>> import array
>>> a = array.array('I', xrange(10**8))  # a.itemsize indicates 4 bytes per element => about 0.5 GB
>>> import random                                                               
>>> random.shuffle(a)

It is also possible to use the third-party NumPy package, which is the standard Python tool for managing arrays in an efficient way:

>>> import numpy
>>> ids = numpy.arange(100000000, dtype='uint32')  # 32 bits is enough for numbers up to about 4 billion
>>> numpy.random.shuffle(ids)

(this is only useful if your program already uses NumPy, as the standard module approach is about as efficient).


Both method take about the same amount of time on my machine (maybe 1 minute for the shuffling), but the 0.5 GB they use is not too big for current computers.

PS: There are too many elements for the shuffling to be really random because there are way too many permutations possible, compared to the period of the random generators used. In other words, there are fewer Python shuffles than the number of possible shuffles!

Answer from Eric O. Lebigot on Stack Overflow
Top answer
1 of 4
9

If you have 100 million numbers like in the question, then this is actually manageable in-memory (it takes about 0.5 GB).

As DSM pointed out, this can be done with the standard modules in an efficient way:

>>> import array
>>> a = array.array('I', xrange(10**8))  # a.itemsize indicates 4 bytes per element => about 0.5 GB
>>> import random                                                               
>>> random.shuffle(a)

It is also possible to use the third-party NumPy package, which is the standard Python tool for managing arrays in an efficient way:

>>> import numpy
>>> ids = numpy.arange(100000000, dtype='uint32')  # 32 bits is enough for numbers up to about 4 billion
>>> numpy.random.shuffle(ids)

(this is only useful if your program already uses NumPy, as the standard module approach is about as efficient).


Both method take about the same amount of time on my machine (maybe 1 minute for the shuffling), but the 0.5 GB they use is not too big for current computers.

PS: There are too many elements for the shuffling to be really random because there are way too many permutations possible, compared to the period of the random generators used. In other words, there are fewer Python shuffles than the number of possible shuffles!

2 of 4
4

Maybe something like (won't be consecutive, but will be unique):

from uuid import uuid4

def unique_nums():  # Not strictly unique, but *practically* unique
    while True:
        yield int(uuid4().hex, 16)
        # alternative yield uuid4().int

unique_num = unique_nums()
next(unique_num)
next(unique_num) # etc...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Creating a Python Sequential Number Generator for Unique IDs - YouTube
Learn how to build a `Python` sequential number generator that creates unique IDs using digits (0-9) and uppercase letters (A-Z). Find step-by-step instructi...
Published: April 15, 2025
Views: 1
๐ŸŒ
Howchoo
howchoo.com โ€บ python โ€บ python-range-function
Use the Python range() Function to Generate Sequences of ...
In Python, comprehensions are a useful construct that allows us to create new sequences in a very concise way.
People also ask

Which method is best for generating N unique numbers from a small range
ANS: For small ranges, random.sample(range(population_size), N) is the recommended, clearest, and most performant method in standard Python.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-unique-random-number-generation-methods
Python Techniques for Generating Unique Random Numbers Without ...
Does random.shuffle produce unique items if the input list already has duplicates
ANS: No, random.shuffle only rearranges the existing elements; it does not remove duplicates. You must deduplicate the source list first, perhaps via list(set(source_list)), as illustrated in Method 16.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-unique-random-number-generation-methods
Python Techniques for Generating Unique Random Numbers Without ...
How to handle an OverflowError when using range(very_large_number)
ANS: Standard Python range() conversion to C types can overflow. Employ custom sampling functions like Method 5 or leverage libraries like NumPy/JAX which handle large integers natively in their random generation pipelines, as shown in Method 20.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-unique-random-number-generation-methods
Python Techniques for Generating Unique Random Numbers Without ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 34287404 โ€บ how-to-generate-sequence-number-in-python
json - How to generate sequence number in python? - Stack Overflow
They're unique and don't need any external state or synchronization (which means way more reliable uniqueness). ... @SergioTulentsev Could be plz elaborate more on how to use it. If you are telling about mongodb object id, I know that. I dont want that in my case. Any other suggestions? ... The problem with sequences is that you need to store its state ("what is the last generated number").
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-generate-sequences-in-Python
How to generate sequences in Python?
February 27, 2025 - Following are the various techniques to generate sequences in Python ? ... We can generate a sequence using a loop by starting with an empty sequence and appending values that meet a specified condition. In the following example, we have generated a sequence of all even numbers below 20 using ...
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ python-unique-random-number-generation-methods
Python Techniques for Generating Unique Random Numbers Without Replacement
July 29, 2025 - Pythonโ€™s random module offers direct and optimized functions for sampling without replacement. The most idiomatic and generally fastest way to obtain k unique items from a population (like a range of numbers) is by using random.sample(). This method is highly optimized internally.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-generate-n-unique-random-numbers-within-range
Generate N unique Random numbers within a Range in Python | bobbyhadz
April 10, 2024 - Copied!from random import choice def gen_random_number(low, high, exclude): return choice( [number for number in range(low, high) if number not in exclude] ) The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise, it evaluates to False. ... The last step is to use the random.choice() method. The random.choice method takes a sequence and returns a random element from the non-empty sequence. ... If the sequence is empty, the method raises an IndexError. If you need to generate N random numbers in a range, excluding a list of numbers, use a list comprehension.
๐ŸŒ
Linux Hint
linuxhint.com โ€บ python-generate-sequence-of-numbers
Linux Hint โ€“ Linux Hint
July 24, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
Find elsewhere
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Generate a unique number for each entry - Python Help - Discussions on Python.org
June 26, 2024 - Started learning Python yesterday; I know little more than what is here, below. The random generator functions but the same number applies to each entry. Could someone show me how to generate a unique number for each entry (one, two, three)? Thank you. Code so far: import random number_gen = random.choice(range(100)) num = str(number_gen) for group in ("Group_A:", "Group_B:"): print(group) print(" one", num) print(" two", num) print(" three", num) print()
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ math โ€บ python-math-exercise-81.php
Python Math: Generate a series of unique random numbers - w3resource
... import random choices = list(range(100)) random.shuffle(choices) print(choices.pop()) while choices: if input('Want another random number?(Y/N)' ).lower() == 'n': break print(choices.pop())
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ python-unique-random-integers
Python Techniques for Generating Unique Random Integer Sequences
November 4, 2025 - To circumvent the OverflowError associated with extremely large range objects in random.sample(), a custom generator function that relies on random.randrange() can be constructed. This function determines the effective population size and ensures it does not exceed what Python can handle internally for the sampling limit. ... import random def robust_random_sample(count, start, stop, step=1): # Calculate the actual, safe number of unique items possible population_size = int(abs(stop - start) / abs(step)) if step != 0 else 0 # Limit requested count to the actual population size effective_count
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ random.html
random โ€” Generate pseudo-random numbers
This module implements pseudo-random number generators for various distributions. For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
๐ŸŒ
GitConnected
levelup.gitconnected.com โ€บ the-fastest-way-to-generate-a-sequence-in-python-a61da7f87852
The fastest way to generate a sequence in Python | by Astronomy not Astrology, hunty... | Level Up Coding
May 14, 2020 - The built-in method range([start, ]stop, [step]) was my first introduction to generating sequences in Python. The optional arguments in the function are shown in square brackets. The range() method generates an immutable object that is a sequence of numbers.
๐ŸŒ
Preshing
preshing.com โ€บ 20121224 โ€บ how-to-generate-a-sequence-of-unique-random-integers
How to Generate a Sequence of Unique Random Integers
December 24, 2012 - Unfortunately, calling this PRNG ... tend to generate a sequence of 10000000 unique values. According to Hash Collision Probabilities, the probability of all 10000000 random numbers being unique is just: Thatโ€™s astronomically unlikely. In fact, the expected number of unique values in such sequences is only about 9988367. You can try it for yourself using Python...
๐ŸŒ
YouTube
youtube.com โ€บ learning software
create sequence of numbers in python with 'range' function - YouTube
In this video we will learn how to use dictionaries and some essential/useful skills while using them in pythonBlog post for this video - https://nagasudhir....
Published: August 10, 2020
Views: 1K
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ built-in โ€บ range()
Python range() - Generate Number Sequence
September 27, 2024 - Discover how to utilize this function ... and list comprehensions. Understand that the simplest form of range() takes one argument: the stop value. Use the range() function to generate numbers from ......
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 59807333 โ€บ find-unique-number-of-sequence-and-reads
python - Find unique number of sequence and reads - Stack Overflow
This can be extended to insertions and deletions by generating the 3 parts for 3 different shifts of the string (and choosing/dealing with the part lengths suitably). So by generating 9 keys for each sequence, and using a dictionary, you can quickly find all sequences that are capable of matching the sequence with 2 errors.