Python: Select an item randomly from a list
Python List: Exercise - 25 with Solution
Select Random Item from List
Write a Python program to select an item randomly from a list.
Use random.choice() to get a random element from a given list.
Example - 1 :
Example - 2 :
Example - 3 :
Sample Solution-1:
Python Code:
# Import the 'random' module, which provides functions for generating random values
import random
# Define a list 'color_list' containing various colors
color_list = ['Red', 'Blue', 'Green', 'White', 'Black']
# Use the 'random.choice' function to select and print a random color from the 'color_list'
print(random.choice(color_list))
Sample Output:
Black
Sample Solution-2:
Python Code:
# Import the 'choice' function from the 'random' module to select a random element from a list
from random import choice
# Define a function named 'random_element' that takes a list 'lst' as a parameter
def random_element(lst):
# Use the 'choice' function to return a random element from the input list 'lst'
return choice(lst)
# Call the 'random_element' function with a list as an argument and print the randomly selected element
print(random_element([2, 3, 4, 7, 9, 11, 15]))
Sample Output:
4
Flowchart:
Python Code Editor:
Previous: Write a Python program to append a list to the second list.
Next: Write a python program to check whether two lists are circularly identical.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics