0

How can i choose random multiple elements from list ? I looked it from internet but couldn't find anything.

words=["ar","aba","oto","bus"]
1

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No worries, mate! Glad to help :)
0

I think about that :

import random as rd
words=["ar","aba","oto","bus"]
random_words = [word for word in words if rd.random()>1/2]

You can adjust 1/2 by any value between 0 and 1 to approximate the percentage of words chosen in the initial list.

Comments

0

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']

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.