Thursday 23 September 2021

Python: select a random item from the list

'random.choice' method can be used to select a random item from a list.

 

Example

random.choice(my_list)

 

select_random_element_from_list.py

import random

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

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

print(select_random_element(primes))
print(select_random_element(primes))
print(select_random_element(primes))

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment