Home > Net >  how do I generate random group names using lists
how do I generate random group names using lists

Time:05-24

I can not figure out my mistake. Can someone help me?

We are supposed to create the lists outside of the function. then create an empty list inside a function. We should return 9 different names.

    first_names = ["Gabriel", "Reinhard", "Siebren"]
    last_names = ["Colomar", "Chase", "Vaswani"]

    def name_generator(first_names, last_names):
        full_name= ()

    import random

    for _ in range(9):
        full_name=random.choice(first_names) " " random.choice(last_names)
        full_name.append(full_name)
    group_string = ", ".join(full_name) 

CodePudding user response:

The problem is that you're using a variable full_name twice: once as a string to store a new name in, and once as the list. This is closer to what you want:

    import random

    first_names = ["Gabriel", "Reinhard", "Siebren"]
    last_names = ["Colomar", "Chase", "Vaswani"]
    full_names = []

    for _ in range(9):
        new_name=random.choice(first_names) " " random.choice(last_names)
        full_names.append(new_name)
    group_string = ", ".join(full_names) 

I'll note that I'd probably use full_names as plural version of the variable name too since it's a list of multiple things.

CodePudding user response:

This makes a list of all possible full names and then picks from what hasn't been taken yet one by one.

remaining = [(a,b) for a in range(len(first_names)) for b in range(len(last_names))]

full_name = []
while len(remaining)>0:
    (a,b) = random.choice(remaining)
    full_name.append(first_names[a]   " "   last_names[b])
    remaining.remove((a,b))
  • Related