I am using random.choice(list), but instead of the function printing out (num) number of names from the list, the list itself is simply being printed (num) number of times instead. I can't figure out what I am doing wrong. This is my first ever question on Stack Overflow.
Here is my code and also the output:
import random
def listgen(num):
newlist=[oglist.split(',')]
for x in range(num):
print(random.choice(newlist))
print("Type in your list. Separate each name by a comma and press enter when finished")
oglist=input()
print("how many random names do you need?")
num=int(input())
listgen(num)
Output:
Type in your list. Separate each name by a comma and press enter when finished
Joe, Frank, Janet, Dion, Rachel, Lilly, Alyx
how many random names do you need?
3
['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']
['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']
['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']
newlist=[oglist.split(',')]
says "Make a list
of the split up contents, and wrap that list
in an outer list
containing the split up list
as its only element". newlist
ends up being [['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']]
(note extra set of outer brackets). random.choice
then "randomly" selects from the one-element outer list
, returning the inner list
every time. Get rid of the outer brackets to have a single layer list
to choose from:
newlist = oglist.split(',')
As a side-note, modern Python can pick multiple items for you without writing your own loop, simplifying listgen
to one of:
def listgen(num):
print(*random.choices(oglist.split(','), k=num), sep="\n")
or if you want to prevent duplicates:
def listgen(num):
print(*random.sample(oglist.split(','), num), sep="\n")