Python numbers | select function ()

Python Methods and Functions

Syntax :

 random.choice (sequence)  Parameters:  sequence is a mandatory parameter that can be a list, tuple, or string.  Returns:  The choice () returns a random item. 

Note: we have to import randomly to use the choice () method.

Below is the implementation of the above approach in Python3 :

# Python3 program to demonstrate usage
# select () method

 
# import random

import random

 
# prints a random value from the list

list1 = [ 1 , 2 , 3 , 4 , 5 , 6

print (random.choice (list1))

 
# prints a random element from a string

string = "striver"  

print (random.choice (string )) 

The output will be different each time as the system returns random item. 
Exit :

 5 s 

Practical application:
Print any random number 5 times from the given list.

# Python3 practical demonstration program
# select ()

 
# import a random module

import random 

 

list1 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10

 

for x in range ( 5 ):

print (random.choice (list1))

The output changes every time the choice () function is used. 
Output:

 1 4 1 5 7 




Tutorials