Python Random Module: Generating Random Numbers and Elements
The Python random module provides functions for generating pseudo-random numbers and performing random actions like selecting elements and shuffling lists. Learn how to use methods like random.random()
to generate random float numbers and more to add variability and unpredictability to your programs.
Python - Random Module
The random module in Python is used to generate pseudo-random variables. It can perform various random actions such as generating random numbers, selecting random elements from a list, shuffling elements, etc. Here are some examples:
Generate Random Floats
The random.random()
method returns a random float number between 0.0 to 1.0. The function doesn't need any arguments.
Example: random()
import random
# Generate a random float between 0.0 and 1.0
print(random.random())
Output
0.123456789
Generate Random Integers
The random.randint()
method returns a random integer between the specified range.
Example: randint()
import random
# Generate a random integer between 1 and 100 (inclusive)
print(random.randint(1, 100))
print(random.randint(1, 100))
Output
56
12
Generate Random Numbers within Range
The random.randrange()
method returns a randomly selected element from the range created by the start, stop and step arguments. The value of start is 0 by default. Similarly, the value of step is 1 by default.
Example: randrange()
import random
# Generate a random number from a range
print(random.randrange(1, 10))
print(random.randrange(1, 10, 2))
print(random.randrange(0, 101, 10))
Output
7
5
50
Select Random Elements
The random.choice()
method returns a randomly selected element from a non-empty sequence. An empty sequence as argument raises an IndexError.
Example: choice()
import random
# Select a random element from a sequence
print(random.choice('computer'))
print(random.choice([12, 23, 45, 67, 65, 43]))
print(random.choice((12, 23, 45, 67, 65, 43)))
Output
m
65
12
Shuffle Elements
The random.shuffle()
method randomly reorders the elements in a list.
Example: shuffle()
import random
# Shuffle elements in a list
numbers = [12, 23, 45, 67, 65, 43]
random.shuffle(numbers)
print(numbers)
random.shuffle(numbers)
print(numbers)
Output
[67, 12, 65, 45, 23, 43]
[12, 23, 67, 45, 43, 65]