Python randomly selects an element or item from list. In this tutorial, you will learn how to randomly select single or n element from a list in python.
.medrectangle-3-multi-320{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:auto!important;margin-right:auto!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:250px;padding:0;text-align:center!important;width:100%}
As well as, this tutorial will help you to selecting random element from list python without repetition.
Python Randomly Select Elements From List
- Python randomly select item or element from the list
- Python randomly select n elements from the list
Python randomly select item or element from the list
To select random items from a list in Python, you will use the random.choice() method. The random choice() is a built-in method that returns a random item from the non-empty sequence-like list. To use the choice() method in your program, you need to import the random package in your file.
import random
Now follow the following instructions to select randomly element or item from list in python.
- First of all, import random in your python program.
- Then declare list of items.
- Use random.choice(data) with list of itmes.
- At the last of program print result.
import random
data = ["samsung", "tata", "amazon", "flipkart", "mi"]
print(random.choice(data))
After executing the program, the output will be:
amazon
Python randomly select n elements from the list
To select random items from a list in Python, you will use the random.sample() method. The random sample() is a built-in method that returns a random items from the non-empty sequence-like list.
Note that, The random.sample() method accepts two arguments which are a list or set and the number of elements, and returns the sample elements.
Now follow the following instructions to select randomly multiple elements or items from list in python.
- First of all, import random in your python program.
- Then declare list of items.
- Use random.select(data) with list of itmes.
- At the last of program print result.
import random
data = ["samsung", "tata", "amazon", "flipkart", "mi"]
print(random.select(data, 2))
If you want to select 2 random elements from the list, and then you will pass 2 as the second argument, which suggests the number of elements you need in the list.
After executing the program, the output will be:
['samsung', 'flipkart']