Generating random Id’s in Python
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)
Output
[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.
Table of Content
Using secrets Module
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)
Output
[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.- List comprehension:This repeats this process 10 times to generate 10 random numbers.
Using uuid
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)
Output
['fb76a31d-6e83-439a-8e91-c973f0ddb4b7', 'c8fe7a1c-f606-4561-ada9-bb21603a0040']
Explanation:
uuid.uuid4():
This
- List comprehension: This creates 2 UUIDs, converting each to a string.
print(res):
This