How can i choose random multiple elements from list ? I looked it from internet but couldn't find anything.
words=["ar","aba","oto","bus"]
How can i choose random multiple elements from list ? I looked it from internet but couldn't find anything.
words=["ar","aba","oto","bus"]
You could achieve that with random.sample():
from random import sample
words = ["ar", "aba", "oto", "bus"]
selected = sample(words, 2)
That would select 2 words randomly from the words list. You can check Python docs for more details.
Use random
Here is example
random.choice>>> import random
>>> words=["ar","aba","oto","bus"]
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
oto
>>> print(random.choice(words))
aba
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
bus
random.sample # sample takes one extra argument to pass a list with element is returned>>> print(random.sample(words, 3))
['bus', 'ar', 'oto']
>>> print(random.sample(words, 3))
['ar', 'oto', 'aba']
>>> print(random.sample(words, 2))
['aba', 'bus']
>>> print(random.sample(words, 2))
['ar', 'aba']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['oto']
>>> print(random.sample(words, 1))
['bus']
You can use random library
Method 1 - random.choice()
from random import choice
words=["ar","aba","oto","bus"]
word = choice(words)
print(word)
Method 2 - Generate Random Index
from random import randint
words=["ar","aba","oto","bus"]
ind = randint(0, len(words)-1)
word = words[ind]
print(word)
Method 3 - Select Multiple Items
from random import choices
words=["ar","aba","oto","bus"]
selected = choices(words, k=2) # k is the elements count to select
print(selected)