Use itertools.count:

from itertools import count

class MyClass(object):
    id_counter = count().next
    def __init__(self):
        self.id = self.id_counter()
Answer from agf on Stack Overflow
๐ŸŒ
Program Creek
programcreek.com โ€บ python
Python generate sequence
def generate_note_sequence(instrument_phrases, note_mats, length, tick_max=160): next_phrase = random.choice(instrument_phrases) phrases = [] sofar = 0 while sofar < length: phrases.append(next_phrase) sofar += sum([next_phrase["tick"][i] for i in xrange(0,len(next_phrase["tick"])) if next_phrase["type"][i] == "on"]) last_pitch = next_phrase["pitch"][-1] last_tick = next_phrase["tick"][-1] last_velocity = next_phrase["velocity"][-1] pitch = find_match(note_mats, last_pitch, note_type="pitch") velocity = find_match(note_mats, last_velocity, note_type="velocity") tick = find_match(note_mats, last_tick, note_type="tick") next_phrase = find_next_phrase(pitch, velocity, tick, instrument_phrases) return phrases ... def generate_note_sequence_id(filename, collection_name, source_type): """Generates a unique ID for a sequence.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 34287404 โ€บ how-to-generate-sequence-number-in-python
json - How to generate sequence number in python? - Stack Overflow
Good news is, you can store them in mongo! db.sequences.find() > { "_id": "alerts", "last_value": 234 } Then you can use findAndModify to generate a new value and return it in the same operation (no race conditions, safe and reliable).
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-generate-sequences-in-Python
How to generate sequences in Python?
February 27, 2025 - tuple_1 = (2,4,6,8) list_comp = ... new sequence in a single line and we can access the items of it. To generate an object by using a generator function we use the yield keyword instead of the return keyword....
๐ŸŒ
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
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 68518710 โ€บ printing-a-list-in-python-and-generating-an-id-column-for-each-item-sequence-of
Printing a list in Python and generating an ID column for each item (sequence of numbers) - Stack Overflow
Using Python I want to print the elements of a list using for loop and also I want to generate a number for each item in the list. Something like an ID column next to the column containing the list's
๐ŸŒ
CodeSpeedy
codespeedy.com โ€บ home โ€บ sequence generator in python
Sequence generator in Python - CodeSpeedy
February 9, 2020 - This article is telling about yield function of Python which is used as sequence generator in Python. There are other sequence generators are also mentioned
Top answer
1 of 1
2

This is some nice-looking Python code. Good work. Though, if you were to run pylint over this, you'd still find:

************* Module cr
cr.py:1:0: C0114: Missing module docstring (missing-module-docstring)
cr.py:44:12: W0612: Unused variable 'i' (unused-variable)

------------------------------------------------------------------
Your code has been rated at 9.20/10

So, it's usually good practice to add a module docstring at the beginning of the module. I've seen many people adding the same docstring as the one for the class within that module (if it's just one).

From PEP8:

All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

So, in the end, it is just a matter of preference.

You also have a magic number: 1000000. I'd just take it out of your __init__ and define it as a constant. Something like:

MAX_RANGE = 1000000

Now, the second pylint warning tells you that here:

for i in range(0, n_ids):  # you're not using i at all
    random_ids.append(self.random())
return random_id

So you could just replace it with _:

for _ in range(0, n_ids):
    random_ids.append(self.random())
return random_id

Even better, you could entirely rewrite the above and use a list comprehension instead:

def randoms(self, n_ids: int):
    """
    Generate list of random ids
    :param n_ids: number of id you need to generate
    :return: list of random ids it might contains duplications
    """

    return [self.random() for _ in range(0, n_ids)]

The same applies for get_unique_ids() method (although some might argue that there's a small benefit in favour of readability):

def get_unique_ids(self):
    """
    :return: list of unique ids it randomize from
    """

    return [
        hashlib.md5(str(i).encode()).hexdigest()
        for i in range(self.__start_num, self.__end_num + 1)
    ]

From this SO answer:

List comprehension is basically just a "syntactic sugar" for the regular for loop. In this case the reason that it performs better is because it doesn't need to load the append attribute of the list and call it as a function at each iteration. In other words and in general, list comprehensions perform faster because suspending and resuming a function's frame, or multiple functions in other cases, is slower than creating a list on demand.

This won't have such a big impact on the actual speed, but it's definitely giving you a nice start :)

Another advice would be to use Numpy if you want to generate large numbers of random ints; if you're just generating one-at-a-time, it may not be as useful (but then how much do you care about performance, really?).

Libraries like Numpy carefully move as much compute as possible to underlying C code.

๐ŸŒ
Camdenreslink
code.camdenreslink.com โ€บ dev โ€บ 7-ways-to-create-sequences-in-python
7 Ways to Create Sequences in Python โ€” Camden Reslink
December 5, 2018 - If each value in your sequence can be calculated using a simple expression (where every value follows some rule), list comprehensions provide a terse and expressive method for creating your sequence. List comprehensions follow the format: [{expression with variable} for {variable} in {iterator} if {condition with variable}] Letโ€™s consider the simple example of generating the first n-even numbers:
๐ŸŒ
Real Python
realpython.com โ€บ python-sequences
Python Sequences: A Comprehensive Guide โ€“ Real Python
March 18, 2026 - The value returned by the built-in id() function is the same before and after the augmented assignment operation. However, the behavior is different when using tuples: ... >>> numbers_tuple = 1, 2, 3 >>> id(numbers_tuple) 4331564032 >>> ...
๐ŸŒ
DataCamp
campus.datacamp.com โ€บ courses โ€บ introduction-to-python-for-finance โ€บ arrays-in-python
Generating a sequence of numbers | Python
The NumPy function arange() is an efficient way to create numeric arrays of a range of numbers. The arguments for arange() include the start, stop, and step interval as shown below: ... Create an array company_ids containing the numbers 1 through 7 (inclusive).
๐ŸŒ
Patrickwalls
patrickwalls.github.io โ€บ mathematicalpython โ€บ python โ€บ sequences
Sequences - Mathematical Python
It is very inefficient to create a sequence by manually typing the numbers. For example, simply typing out the numbers from 1 to 20 takes a long time! numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] print(numbers) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Python has a beautiful syntax for creating lists called list comprehensions.
๐ŸŒ
Magedsaeed
magedsaeed.github.io โ€บ generate-sequences
Generate Sequences Docs
generate-sequences is a Python library for generating sequences from deep learning architectures with support for greedy search, beam search, and customizable configurations. This package generates sequences from architectures developed with PyTorch.
๐ŸŒ
Medium
medium.com โ€บ @nagasudhirpulla โ€บ create-sequences-with-range-function-in-python-6b98a0fbbf8b
Create sequences with range function in python | by Naga Sudhir | Medium
August 21, 2021 - # create sequence from 2 to 12 with steps of 2, i.e., 2,4,6,8,10,12 x = range(2,13,2)# iterate over the sequence using for loop and in operator for n in x: print(n) # this code should print 2,4,6,8,10,12 in each line of the console
๐ŸŒ
DEV Community
dev.to โ€บ kalebu โ€บ how-to-generate-unique-ids-in-python-3n8k
How to generate unique IDS in python - DEV Community
May 22, 2022 - This can be achieved using the python UUID module, which will automatically generate a random ID of which there less than one chance in a trillion for ID to repeat itself.