How to Create a Random UUID String in Python — CODEFATHER

Claudio Sabato
2 min readNov 25, 2023

This article will guide you through the process of generating a random UUID (Universally Unique Identifier) string using Python.

What is a UUID?

A UUID is a 128-bit number you can use to uniquely identify information in computer systems. The term “universally unique identifier” suggests that this ID is unique, which is nearly true, given the huge number of possible UUIDs.

As a developer, it’s important for you to understand why you would use a UUID.

Some common applications of UUIDs are:

  • Web Development: Session IDs, token generation.
  • Databases: Unique keys in databases.
  • Distributed Systems: Unique IDs across different machines.

Generating a Random UUID in Python

To generate a random UUID in Python you can use the uuid module that can generate several types of UUIDs. The most common type is UUID v4 which you can generate using the uuid4 function of the uuid module.

>>> import uuid
>>> uuid.uuid4()
>>> type(uuid.uuid4())
<class 'uuid.UUID'>

As you can see, the object you get back is of type uuid.UUID. To convert it into a string you can use the str() built-in function.

>>> str(uuid.uuid4())

You now have a Python string that represents a UUID.

If you want to explore UUIDs further, below you can also see four functions available in the uuid module to generate UUIDs (including uuid4 which you have just used).

Let’s see what all the types of UUIDs look like with quick examples of code:

UUID1: Generated based on the host computer’s MAC address and the current time.

>>> uuid1 = uuid.uuid1()
>>> print("UUID1:", uuid1)
UUID1: 4495519a-8bc8-11ee-8285-1e00d11a7245



Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.