When you need to use random values in Python, you can count on the built in module random. Let’s explore it.
random.random
Random.random will return a number among 0 and 1 (a float)
random.random
from random import random
for i in range(5):
print(random())
shuffle
Shuffle can be used to mix a list of item (lists are what arrays are for other programming languages, in python).
Let’s see an example:
from random import shuffle a = [1,2,3,4] print("This is before shuffle:{}".format(a)) shuffle(a) print("This is after: {}".format(a))
Interactive Python shell (you can change the values)
shuffle
from random import shuffle
a = [1,2,3,4]
print("This is before shuffle:{}".format(a))
shuffle(a)
print("This is after: {}".format(a))
Choice
You can pick a random number from a list with choice
choice: pick a random number
from random import choice
a = [1,2,3,4]
x = choice(a)
print("This is the number: {}".format(x))
y = choice(a)
print("This is another number: {}".format(y))
Choices
This is like sample, but return a list of elements from another list. Differently from sample (see below) it can return more of the same element.
import random a = [1, 2, 3, 4, 5, 6, 7] x = random.choices(a, k=3) print("This are taken from a (can be also the same): {}".format(x)) y = random.choices(a, k=10) print("You can have more elements than the original list: {}".format(x))
Sample
Return a list of unique elements from a list. You can take, for example, 3 elements of a list of 10 elements and each one of the 3 elements cannot be the same element (without replacement, i.e. without putting the element back in the list).
random.sample
from random import sample
a = [1, 2, 3, 4, 5, 6, 7]
x = sample(a, 3)
print("This are different elements of a: {}".format(x))
Randint
As the name says: it gives you a random integer number from a starting numnber to an ending number (comprised).
randint
import random
a = [1, 2, 3, 4, 5, 6, 7]
for i in range(10):
x = random.randint(1,10)
print(x)
Randrangerandom.
randrange
(start, stop[, step])
With this one you get a random number between start and stop. You can also give a step among every possible number. If you set start=10 and stop=100 with a step=20, for example, you will have 10, 30, 40… 100.
Look at this example here (press run to see the result)
Randrange
import random
for i in range(5):
x = random.randrange(0, 100, 25)
print(x)