A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/generating-random-ids-python/ below:

Generating random Id's in Python

Generating random Id's in Python

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

Python
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:

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.

Python
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:

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.

Python
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:



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