Search code examples
pythonlistfunctionrandomsplit

How to take a string, create a list from string, and select randomly from that list (x) times


I want to create a Python function which will take names as input separated by commas; turn that string into a list, and finally choose (num - parameter) number of names from that list.

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.

  • I am importing random module
  • I am using split to delineate names by commas
  • (num) parameter should help print randomly chosen names (num) times

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


Solution

  • 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")