How to generate unique IDS in python
1 min read

How to generate unique IDS in python

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()
UUID('4a59bf4e-1653-450b-bc7e-b862d6346daa')

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))

Output

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

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

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