In Python, we can easily select a random element from a list by using the random
module.
This module contains a function called choice()
which selects a random element from a given list.
Here is an example code that randomly selects an element from a list:
import random # Create a list my_list = [1, 2, 3, 4, 5] # Select a random element from the list random_element = random.choice(my_list) # Print the random element print(random_element)
In this code, we first import the random
module.
Then, we create a list called my_list
that contains some elements.
Finally, we use the choice()
function to select a random element from the list and store it in the random_element
variable.
We then print the value of random_element
to the console.
You can run this code to see the output. Each time you run the program, you will get a different random element from the list.
This method is very useful when you want to select a random item from a list of items, such as selecting a random card from a deck of cards, or selecting a random question from a list of interview questions.
In conclusion, selecting a random element from a list in Python is very easy.
We just need to import the random
module and use the choice()
function to select a random element from the list.