DEV Community

Cover image for How to generate unique IDS in python
Jordan Kalebu
Jordan Kalebu

Posted on • Updated on

How to generate unique IDS in python

In this article, you’re going to learn how to auto-generate unique IDs in Python.

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.

basics of UUID

UUID module comes with the python standard library therefore, you don’t need to install anything.

creating a unique random id

To create a random id, you call the uuid4 () method and it will automatically generate a unique id for you just as shown in the example below;

  • Example of usage
>>> import uuid
>>> uuid.uuid4()
Enter fullscreen mode Exit fullscreen mode

Sample Project

For instance, we want to generate a random unique ID for students in class using UUID, our code will look as shown below;

from uuid import uuid4

students = ['James', 'Messi', 'Frederick', 'Elon']

for student in students:
    unique_id = str(uuid4())
    print('{} : {}'.format(student, unique_id))
Enter fullscreen mode Exit fullscreen mode


kalebu@kalebu-PC:~$ python3 
James : 8bc80351-1c1a-42cf-aadf-2bedadbc0264
Messi : 4765f73c-4fb4-40a3-a6f3-cac86b159319
Frederick : 9692cafb-0175-4435-88fd-54bcd2135230
Elon : 903daf6c-8ced-4971-bbf3-e03c8083a34b
Enter fullscreen mode Exit fullscreen mode

I recommend also reading this;

Hope you find this post interesting, now don't be shy, feel free to share it with your fellow developers.

The original article can be found on

In case of any suggestion or comment, drop it in the comment box and I will get back to you ASAP.

Top comments (1)

paul_rogers_e00c8e4549cde profile image
Paul Rogers • Edited

There are a number of "devil in the details" issues regarding using uuid4() for random IDs. UUIDs are not universally unique, regardless of the name. But that's actually OK, because what you really want is contextually unique, i.e., uniqueness of some number of N IDs used in some context. But that uniqueness is actually a probability of collision in those N IDs, and although low, it can never be zero for randomly generated IDs. That is, after all, a consequence of using randomness in the process of generating the IDs.