How To Auto Generate Id In Python

In this tutorial, we will learn how to auto-generate IDs in Python. Auto-generating IDs is useful when you want to uniquely identify items, such as in databases or data storage systems. By using libraries like uuid and techniques like the random and counter-based ID generations, we can create unique identifiers without manual input.

Step 1: Using the UUID Library

Python’s built-in library, uuid, allows us to generate unique identifiers called Universally Unique Identifier (UUID). A UUID is a 128-bit number and can be used to identify items without human-readable names. There are different versions of UUID, but we will use version 4 (random-based) for generating unique IDs.

First, you need to import the uuid library:

Then, you can generate a UUID using the uuid4() function:

The output will be a unique ID similar to the one shown below.

Step 2: Using Incremental Counter IDs

Another method of auto-generating unique identifiers is by using an incremental counter. This means that each new ID will be the previous ID plus one.

First, initialize the counter variable:

Then, you can generate a new ID by incrementing the counter:

Repeat the above step to generate new unique IDs.

Step 3: Using Random Integer IDs

Another method of auto-generating unique IDs is by using random integers. You can use Python’s random library to generate random numbers within a specified range.

First, import the randint function from the random library:

Next, define the range for generating random IDs:

Finally, generate a random ID using the randint() function:

Keep in mind that this method might generate duplicate IDs, so it’s essential to ensure the uniqueness of the generated IDs.

Full Code

The output will display unique IDs generated using UUID, incremental counter, and random integer methods.

UUID: d4bf1af7-4336-4efd-b832-950cf41c0d00
Counter ID: 1
Random ID: 5497


In this tutorial, we learned different methods of auto-generating unique IDs in Python using the uuid library, incremental counter, and random integers. The choice of method depends on your requirements and the level of uniqueness you need. UUIDs offer a higher guarantee of uniqueness, while counter-based and random-based implementations can still risk duplicate IDs but are easier to manage and read.