
Problem –
You want to randomly pick items from a list or a sequence or generate random numbers.
Solution –
The random module in python has various functions related to random numbers.
To randomly pick items from a list we can use the random.choice() function.
In [1]: import random
In [2]: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [3]: # randomly pick a item from a list
In [4]: random.choice(numbers)
Out[4]: 4
In [5]: random.choice(numbers)
Out[5]: 6
In [6]: random.choice(numbers)
Out[6]: 6
In [7]: coin = ['Heads','Tails']
In [8]: random.choice(coin)
Out[8]: 'Heads'
In [9]: random.choice(coin)
Out[9]: 'Heads'
To take a sample of N items from the list, use the random.sample() function.
In [10]: random.sample(numbers, 2)
Out[10]: [5, 9]
In [11]: random.sample(numbers, 4)
Out[11]: [3, 5, 1, 10]
In [12]: random.sample(numbers, 4)
Out[12]: [8, 4, 2, 7]
If you want to randomly shuffle items in place then use the random.shuffle() function.
In [13]: random.shuffle(numbers)
In [14]: numbers
Out[14]: [4, 3, 1, 10, 9, 7, 5, 2, 8, 6]
In [15]: random.shuffle(numbers)
In [16]: random.shuffle(numbers)
In [17]: numbers
Out[17]: [10, 5, 3, 7, 2, 6, 1, 8, 9, 4]
To produce random integer between two numbers use random.randint() function.
In [18]: random.randint(0, 10)
Out[18]: 4
In [19]: random.randint(0, 10)
Out[19]: 8
In [20]: random.randint(0, 100)
Out[20]: 12
In [21]: random.randint(0, 100)
Out[21]: 42
To produce random floating point value between 0 and 1 use the random.random() function.
In [22]: random.random()
Out[22]: 0.5657755727314651
In [23]: random.random()
Out[23]: 0.5966024924367329
In [24]: random.random()
Out[24]: 0.6170897474999034