Random Module Functions

Python Documentation

random — Generate pseudo-random numbers

Quick Notes/Examples

from random import shuffle names: list[str] = [ 'Alex', 'Barbara', 'Charles', 'Gretchen', 'Jason', 'Judy', 'Marie', 'Tom' ,'Zoe' ] # ---- randomize a list (shuffle the list in place) shuffle(names) print(names)

from random import random, randint, randrange # ---- random (random float in the range 0.0 <= X < 1.0) value: float = random() print(f'random() is {value}') # ---- randint (random integer upper bound is included) values: list[int] = [randint(10,20) for _ in range(5)] print(randint() = {values}) # ---- randrange (random elements from range, upper bound is excluded) values2: list[int] = [randrange(0,3) for _ in range(5)] print(randrange() = {values2}) values3: list[int] = [randrange(0,10,2) for _ in range(5)] print(randrange(with step = 2) = {values3})

from random import choice, choices names: list[str] = ['Tom', 'Judy', Jason', 'Barbara', 'Marie', 'Gretchen'] # ---- select a random element from the list print(f'choice() = {choice(names)') # ---- select several random elements from the list # ---- (the same element may be selected more that once) print(f'choices() = {choices(names,k=3)}') # ---- use selection weights (sum to 1.0) # ---- (percentage probability a give element # ---- will appear in the selected list) weights: tuple = (.10, , .20, .05, .25, .21, .29) print(f'choices() = {choices(names,k=3,weights=weights)}')

from random import sample # ---- the similar to choices except it will only # ---- draw each element once from the list # ---- every element in the list is considered unique # ---- (e.g. [10, 10, 6, 7, 8] are all unique values) print(samples(range(100),k=10) # ---- something else we can do colors: list[str] = ['r','g','b'] print(sample(colors,k=5,counts=(10,20,5)))

from random import seed # ---- seed allows us to get consistent results back # ---- (very important for testing) seed(1491) # generate the same random values each time