Last Updated : 07 Jan, 2025
Generating random IDs in Python is useful when we need unique identifiers for things like user accounts, sessions, or database entries. In this article we will see Various methods to Generate Random ID's in Python.
Using random.randint()random.randint()
method in Python is used to generate random integers within a specified range. It's a simple and efficient way to create random IDs for various purposes like user IDs or order numbers. This method guarantees that the generated numbers will fall between the given lower and upper bounds (inclusive).
import random
# Generate 10 random IDs between 1 and 100
res = [random.randint(1, 100) for _ in range(10)]
print(res)
[88, 21, 41, 77, 97, 43, 8, 9, 85, 36]
Explanation:
random.randint(1, 100):
This generates a random integer between 1 and 100.[random.randint(1, 100) for _ in range(10)]
:This repeats this 10 times to create a list of 10 random numbers.secrets
module is part of Python's standard library and is designed for cryptographically secure random numbers, making it suitable for applications where security is required.
import secrets
# Generate 10 secure random IDs between 1 and 100
res = [secrets.randbelow(100 - 1 + 1) + 1 for _ in range(10)]
print(res)
[46, 3, 34, 17, 18, 90, 36, 16, 42, 31]
Explanation:
secrets.randbelow(100)
:This generates a random number between 0 and 99.+ 1
:This shifts the range to 1–100.If we need globally unique random IDs (rather than simple integer IDs), the uuid
module can be used to generate a universally unique identifier (UUID) based on random values.
import uuid
# Generate 10 UUID random IDs
res = [str(uuid.uuid4()) for _ in range(2)]
print(res)
['fb76a31d-6e83-439a-8e91-c973f0ddb4b7', 'c8fe7a1c-f606-4561-ada9-bb21603a0040']
Explanation:
uuid.uuid4():
This
generates a random UUID.print(res):
This
displays the list of UUIDs.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4