Random Library in Python: The Complete Guide
Working with random numbers is one of the basic tasks in programming. Whether you're creating a simple game, simulating probabilistic events, or working with machine learning, the random library in Python will be a reliable assistant for the developer.
In this material, we will take a detailed look at the effective use of the random library in Python. We will analyze the randint function and compare it with its analogue from the NumPy library.
What is the random library?
The random library is a standard Python module. It is designed to generate pseudo-random numbers. The module does not require additional installation. The library provides a wide range of functions for generating random numbers, selecting random elements from sequences, and shuffling data.
Key Features of the random Library
- Generating random numbers of various types
- Selecting a random element from a list or tuple
- Shuffling elements in collections
- Generating random numbers according to a normal distribution
- Creating random sequences
- Working with probabilistic distributions
Import and getting started with random
To start working with the library, simply import the module in the standard way:
import random
After importing, all functions of the random module become available for generating random data.
Basic Functions of the random Library
Function random.random()
The function generates a random floating-point number in the range from 0.0 to 1.0. The number does not include the upper bound.
import random
print(random.random()) # Possible result: 0.7345832
Function random.randint() and its features
The random.randint() function is one of the most popular functions of the module. It generates a random integer in a given range. An important feature is the inclusion of both range boundaries.
random.randint(a, b) # Returns a random number from a to b inclusive
Practical application of the randint function:
number = random.randint(1, 10)
print(f"Случайное число: {number}")
Result: a random number from 1 to 10 inclusive.
Function random.choice()
The function selects a random element from the passed sequence. It works with lists, tuples, strings, and other iterable objects.
colors = ['red', 'blue', 'green', 'yellow']
selected_color = random.choice(colors)
print(selected_color) # Possible result: 'blue'
Function random.shuffle()
The function shuffles the elements of the list directly in place. Changes the original list without creating a new object.
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(deck)
print(deck) # The elements will be arranged in random order
Additional random Functions
Function random.uniform()
Generates a random floating-point number in the specified range:
value = random.uniform(1.5, 5.5)
print(value) # Random number between 1.5 and 5.5
Function random.sample()
Returns a random sample from a sequence without repetition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sample = random.sample(numbers, 3)
print(sample) # Three random numbers without repetition
NumPy and the np.random.randint function
What is np.random.randint?
The np.random.randint function is an analogue of random.randint from the NumPy library. It is used to work with arrays and vectorization of numerical data. The function is more often used in scientific calculations and machine learning when it is necessary to generate arrays of random numbers.
import numpy as np
arr = np.random.randint(1, 10, size=5)
print(arr) # Possible result: [3 7 2 9 1]
Comparison of random.randint and np.random.randint
| Criterion | random.randint |
np.random.randint |
|---|---|---|
| Return value | One number | Number array |
| Scope | Simple tasks | Scientific calculations, machine learning |
| Productivity | Low for large volumes | High thanks to NumPy optimization |
| Dependencies | Standard library | Requires NumPy installation |
When to use random or np.random
Using the random library
Apply the standard random library in the following cases:
- You need to get one random value
- Working with small lists or simple data structures
- You are creating simple games or applications
- High performance is not required when generating many values
Using np.random
Choose NumPy to work with random numbers when:
- Working with large data sets
- Need to create multidimensional arrays
- Modeling complex mathematical processes
- Developing machine learning algorithms
- Need for high performance
Installing NumPy
If the NumPy library is not already installed on the system, use the command:
pip install numpy
Managing random number generation
Function random.seed()
The function allows you to set the initial value for the random number generator. This ensures the reproducibility of results during testing.
random.seed(42)
print(random.randint(1, 10)) # Will always be the same number
Function np.random.seed()
Similar functionality is available in NumPy:
np.random.seed(42)
arr = np.random.randint(1, 10, size=5)
print(arr) # Reproducible result
Practical applications
Creating a list of random numbers
Generating a list of random numbers using list comprehension:
numbers = [random.randint(1, 100) for _ in range(10)]
print(numbers)
Generating multidimensional NumPy arrays
Creating a two-dimensional array of random numbers:
matrix = np.random.randint(0, 10, size=(100, 100))
print(matrix.shape) # (100, 100)
Working with normal distribution
Generating numbers according to a normal distribution:
# Standard library
normal_number = random.gauss(0, 1) # average=0, standard deviation=1
# NumPy
normal_array = np.random.normal(0, 1, size=1000)
Security and cryptography
It is important to note that the random module is not suitable for cryptographic purposes. To generate cryptographically strong random data, use the secrets module:
import secrets
# Generating a secure random number
secure_number = secrets.randbelow(100)
# Token generation
token = secrets.token_hex(16)
Optimizing work with random numbers
Performance with large amounts of data
When working with large amounts of data, NumPy significantly outperforms the standard random library in terms of execution speed. This is due to the optimized implementation in C and the vectorization of operations.
Choosing the right distribution
Depending on the task, choose the appropriate distribution:
- Uniform distribution for simulations
- Normal distribution for modeling natural phenomena
- Exponential distribution for modeling waiting time
Debugging and testing
When developing applications that use random numbers, it is important to ensure the reproducibility of results for testing. Use fixed seed values during development and testing, removing them in the production version.
Conclusion
The random library in Python is a powerful and simple tool for generating random data. When working with arrays and complex scientific tasks, np.random from the NumPy library comes to the rescue. The choice between these tools depends on the specific requirements of the project.
Understanding the differences between random.randint and np.random.randint allows you to make informed decisions when choosing the right tool. For simple tasks, the standard library is sufficient, for scientific calculations and machine learning, NumPy is preferable.
When planning to study data analysis or machine learning, it is recommended to master working with NumPy and its random data generation capabilities. This will ensure more efficient work with large amounts of data and complex mathematical operations.
The Future of AI in Mathematics and Everyday Life: How Intelligent Agents Are Already Changing the Game
Experts warned about the risks of fake charity with AI
In Russia, universal AI-agent for robots and industrial processes was developed