Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print two random, different names from a set of names

Tags:

python

random

import random  
mylist = ['anthony', 'kris', 'james', 'vinny', 'joe']  
randomList1 = random.randrange(0,len(mylist))  
randomList2 = random.randrange(0,len(mylist))  
name2 = mylist[randomList1]  
name3 = mylist[randomList2]  
print 'The group will consist of', name2, 'and', name3,'. '

Is the code in question, this isn't for me but the person doing it is trying to print two random names from mylist, but of course with the current code it occasionally will print two of the same

The solution given here may be of some use for answering, but I've tried a few things to help him but I'm no python expert and I can't think straight at the moment.

like image 618
user995266 Avatar asked Aug 11 '26 14:08

user995266


2 Answers

Use random.sample:

>>> import random  
>>> mylist = ['anthony', 'kris', 'james', 'vinny', 'joe']
>>> random.sample(mylist, 2)
['james', 'vinny']
like image 152
phihag Avatar answered Aug 13 '26 04:08

phihag


>>> from random import sample
>>> mylist = ['anthony', 'kris', 'james', 'vinny', 'joe']
>>> sample(mylist,2)
['kris', 'vinny']
like image 26
MattH Avatar answered Aug 13 '26 03:08

MattH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!