Python | Select a random item from a list in Python
Here in this article, I am going to let you know how to select a random item from a list and get its value in Python.
I am going to show the easiest way of getting a random item from Python list using the random library. From the library, we are going to use random.choice() function.
Before we start writing our Python code, let me tell you about the random.choice() function in brief.
The random.choice() function of the library return a random element from a Python list or from a tuple or even a string. The choice() method of the library will help to randomly select an item.
Below is the syntax of the function:
In the above syntax, the sequence can be a list or tuple or string.
Now let’s see our example Python code to select a random item value from a list in Python:
import random item_list = ['Ice', 'Fire', 'Water', 'Wind', 'Land'] random_item = random.choice(item_list) print(random_item)
In the above code, first of all, we have imported our library which is necessary for our task. After that, we have created our list that contains some items. Then we have used the random.choice() function to get a random item from our list and store it in a variable. In the end, we print it to see the value of the randomly selected item.
Now you can test the above code in your system to test it. You will able to see randomly selected item value as the result. Every time you run the above code, you will see value from one of the items of our list.
I hope, you will be able now to get a random item from a Python list.
- Digit Addition: How to add Digits of a given integer in Python?
- Switch Case In Python – (Replacement)