Random Number Generation in Python
The Python random module offers a range of functions for generating pseudo-random numbers and performing random operations on sequences. This page covers some of the most commonly used functions for random number generation and list manipulation.
Vocabulary: Pseudo-random numbers are generated by algorithms that produce sequences of numbers that appear random but are actually deterministic.
Generating Random Floating-Point Numbers
The uniform()
function generates a random floating-point number within a specified range.
Example:
import random
print(random.uniform(4, 10))
# Output: 8.45757786453727
This function is useful when you need a random Python number with decimal places within a specific range.
Generating Random Integers
For random integer generation, the randint()
function is used.
Example:
import random
print(random.randint(4, 10))
# Output: 7
This function is particularly useful for simulating dice rolls or any scenario requiring Python losowanie liczb z zakresu (random number selection from a range).
Selecting Random Items from a List
The sample()
function allows you to select a specified number of unique items from a list randomly.
Example:
import random
lista = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
print(random.sample(lista, k=5))
# Output: [150, 80, 110, 90, 50]
This function is excellent for Python losowanie z listy (random selection from a list) without replacement, ensuring each item is selected only once.
Shuffling a List
The shuffle()
function randomly reorders the elements of a list in place.
Example:
import random
lista = [4, 6, 5, 11, 23, 45, 165, 7]
random.shuffle(lista)
print(lista)
# Output: [7, 4, 11, 165, 23, 5, 6, 45]
This function is useful for randomizing the order of items, such as shuffling a deck of cards or randomizing a playlist.
Highlight: Remember to always import random Python at the beginning of your script to use these functions.