Wednesday, 22 September 2021

Python: Select random item from a list

'random.choice(seq)' method return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

 

Example

random.choice(my_list)

 

Find the below working application.

 

select_random_item.py

import random

def get_rand_item(my_list):
    return random.choice(my_list)

my_list = [2, 3, 5, 7, 11, 13, 17, 19]

print(get_rand_item(my_list))
print(get_rand_item(my_list))
print(get_rand_item(my_list))

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment