Using UUID in Python

Python has a library named UUID (Universal Unique Identifier) to generate a random object of 128 bits. This library generates unique IDs based on the system time and the network address of the computer. The UUID object is immutable and it contains some functions to create various unique IDs.  UUID is used for many purposes, such as creating a unique random ID, an ID-based MAC address, cryptographic hash values, or random documents. This tutorial will show you how you can create different types of UUID libraries by using different UUID functions.

Example 1: Create UUID based on system time and MAC address

The following example shows the use of the uuid1() function of the uuid module to generate various UUID values and to read and print the different property values of the UUID object. A UID object is defined by calling the uuid1() method to generate a unique id based on the system time and MAC address. Next, the normally generated ID, the corresponding bytes value, the integer value, and the hex value of the ID are printed.  The version, fields, node, and time properties of the ID are then printed in the next part of the script.

#!/usr/bin/env python3
#Import uuid module
import uuid
# Create random id using uuid1()
UID = uuid.uuid1()
# Print the normal ID
print ("The normal value: ",UID)
# Print the byte ID
print ("The byte value: ",repr(UID.bytes))
# Print the integer ID
print ("The integer value: ",
# Print the hex ID
print ("The hex value: ",UID.hex)
# Print the version number
print ("The version is :", UID.version)
# Print the field values
print ("The fields are: ", UID.fields)
# Print the MAC value in hex
print ("The node value is: ", hex(UID.node))
# Print the time value
print ("The time value is: ", UID.time)


The following output will appear after running the script. The output shows that the default ID value was generated in hex format by separating the distinct parts with a hyphen. The last part of the ID value contains the MAC address, which will always be the same. The node property of the ID object contains the MAC address.

Example 2: Generate SHA-1 and MD5 values of the hostname using uuid3() and uuid5()

An important use of UUID is to create cryptographic hash values The. uuid3() and uuid5() functions of the uuid module are used to generate MD5 and SHA-1 values. In the following script, a tuple variable named hosts is declared with three valid URL addresses. The values of the tuple are iterated using the for loop. The MD5 and the SHA-1 values of each URL are then calculated and printed in each iteration of the loop.

#!/usr/bin/env python3
# import uuid module
import uuid
# Define of a tuple of three hostnames
hosts = ('', '', '')
# Iterate the values of the tuple using loop
for hostname in hosts:
  # Print the hostname
  print("Hostname: ",hostname)
  # Use uuid5() to get SHA-1 value
  print('\tThe SHA-1 value :', uuid.uuid5(uuid.NAMESPACE_DNS, hostname))
  # Use uuid3() to get MD5 value
  print('\tThe MD5 value   :', uuid.uuid3(uuid.NAMESPACE_DNS, hostname))


The following output will appear after running the script.

Example 3: Create random numbers using uuid4()

If you wish to generate the UUID randomly, then you should use the uuid4() function of the uuid module. The following script will generate five UUIDs based on random values via the uuid4() method. The while loop is used here to call the uuid4() method five times and print the randomly generated UUID values.

#!/usr/bin/env python3
# import uuid module
import uuid
# Initialize the variable
i = 1
# Iterate the loop five times
  # Generate a random number
  print("No-", i,' ', uuid.uuid4())
  # Increment the value by one
  i = i + 1


The following output will appear after running the script. If you run the script multiple times, then it will generate different UUIDs at different times.

Example 4: Create sorted UUID from a list using UUID object

The following script shows how you can convert the items of a list into UUIDs and print the values after sorting. Here, the list_ids variable is declared with four list items, where each item value must be in valid UUID format. First, the original values of the list_ids are printed. Next, each item value of the list is converted into UUID using a loop in the try block. If the list_ids contains any item value that does not match the UUID format, then a ValueError exception will be generated, and an error message will be printed. If no error occurs at the time of conversion, then the converted UUIDs are sorted using the sort() method. Next, the sorted UUID values are printed using the for loop.

#!/usr/bin/env python3
# import uuid module
import uuid
# Create a list of IDs of valid format
list_Ids = [
# Print the list values using loop
print('\nThe values of  the list:')
for val in list_Ids:
  print (val)
# The values of list will be converted into uuids and sorted
  uuids = [ uuid.UUID(s) for s in list_Ids ]
  print('\nThe values of the sorted uuids:')
  for val in uuids:
    print (val)

except ValueError:
  # Print error message if any value of the list is in invalid format
  print('Badly formed hexadecimal UUID string')


The following output will appear after running the script. Here, all the items in the list are in the correct UUID format. So, no ValueError will be generated. The first part of the output printed the original list items, and the second part of the output printed the sorted values of the UUIDs.


You may be required to generate UUID in Python for various programming purposes. This tutorial showed you how to generate various UUIDs using a variety of methods. After reading this article and practicing the included examples, you should be able to create UUIDs according to your programming needs.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.