Linux

Python Random module

The Python random module contains very useful type of functions.

randint()

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.

choice(rnlist)

The choice() function return the random value from the list.
Syntax
random.choice(rnlist)
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.

shuffle()

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

randrange()

It returns the random number slected from range (start, stop, step).
Syntax
random.randrange(start, stop[, step])
start
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.

sample

The sample() function is used to obtain a sample from the sequence (string, list, tuple)
Syntax
random.sample(sequence, length)
Sequence
can be a string , list or tuple
length specify 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).




admin