Random Element in List

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") subgraph Lab Skills python/comments -.-> lab-13712{{"`Random Element in List`"}} python/lists -.-> lab-13712{{"`Random Element in List`"}} python/tuples -.-> lab-13712{{"`Random Element in List`"}} python/function_definition -.-> lab-13712{{"`Random Element in List`"}} python/importing_modules -.-> lab-13712{{"`Random Element in List`"}} python/using_packages -.-> lab-13712{{"`Random Element in List`"}} python/standard_libraries -.-> lab-13712{{"`Random Element in List`"}} python/math_random -.-> lab-13712{{"`Random Element in List`"}} end

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 from lst.
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.

Other Python Tutorials you may like