Introduction
In Python, you can easily get a random element from a list using the random module. This module provides a function called choice() which returns a random element from a given list. In this challenge, you will be asked to write a function that takes a list as an argument and returns a random element from that list.
Random Element in List
Write a function random_element(lst) that takes a list as an argument and returns a random element from that list.
- Use
random.choice()to get a random element fromlst.
from random import choice
def sample(lst):
return choice(lst)
sample([3, 7, 9, 11]) ## 9
Summary
In this challenge, you learned how to get a random element from a list in Python using the random module. You also wrote a function that takes a list as an argument and returns a random element from that list. This is a useful skill to have when working with lists in Python.