Python Random module

The Python random module contains a very useful type of functions.


Just import Python random module.
random.randint(start, end)
The function randint() generates the random number between start and end range.
Python randint()
Python randint()
Click to view code
if integer start and end are not defined then error will be ranised.


The choice() function return the random value from the list.
Here random value would be generated from list rnlist.
Python random.choice(list)
Python random.choice(rnlist)
Click to view code
In our code we print three random value from the list.


The shuffle function, shuffles the elements in list in place. random.shuffle(list1)
is the list provided by user.
Let's discuss the example
Python random.shuffle(list1)
Python random.shuffle(list1)
Click to view code
the new list will be different from the previous list.


It returns the random number slected from range (start, stop, step).
random.randrange(start, stop[, step])
and stop spcify the range of random numbers.
step Step to be added in a random number. Let's discuss the example
Python random.randrange(start, stop[, step])
Python random.randrange()
Click to view code
In above code, three random numbers are printed.


The sample() function is used to obtain a sample from the sequence (string, list, tuple)
random.sample(sequence, length)
can be a string , list or tuple
The length specifies the length of sample to be obtained .
Python random.sample()
Python random.sample()
Click to view code
The sample() function return the list of samples, whatever the input is given. The sample() function can be used as shuffling, if length is equal to len(sequence).