How do I let a randomizer (in Python) that makes 2 answers NOT make the same answer twice?

3416 views python-3.x
4

Noob programmer here,

I made a simple randomizer in Python that gives 2 answers, sometimes the answers are the same. How do I prevent this?

Little rundown of the code:

import random
Names = [ ‘Jake’ , ‘John’ , ‘David’ ]

Namesoutcome = random.choices(Names, k=2)

Answer example: [‘Jake’ , ‘Jake’]

I need 2 different answers, plz help!

answered question

It sounds like you want random.sample.

1 Answer

9

I think you want to use random.sample not random.choices

import random
names = [ 'Jake' , 'John' , 'David' ]

answers = random.sample(names, k=2)
answers

outputs

['Jake', 'John']

sample() give unique elements, whereas choices() allows for replacement.

posted this

Have an answer?

JD

Please login first before posting an answer.