0

I am tying to generate a random list of names from a given set. I have tried two different ways (group_1) and group_2 below, but both times I am not able to generate a list of names as desired. While group_1 makes each character into a separate element of the lsit, group_2 just makes a single element list. while i need list of 342 elemetns.

code:

import random
first_names=('John','mary','hillary')
last_names=('Johnson','Smith','Williams')

group_1=list(" ".join(random.choice(first_names)+" "+random.choice(last_names) for _ in range(342)))
group_2 = [" ".join(random.choice(first_names)+" "+random.choice(last_names) for _ in range(342))]

print(group_1)
print(len(group_1))
print(group_2)
print(len(group_2))

2 Answers 2

2

The unnecessary " ".join is what's causing this problem, you can just omit it (since you already have + " " +) and use a list comprehension:

group = [random.choice(first_names) + " " + random.choice(last_names) for _ in range(342)]

print(len(group))
print(group)

Output:

342
['hillary Johnson', 'John Williams', 'John Johnson', 'mary Williams', 'mary Smith', ...]
Sign up to request clarification or add additional context in comments.

Comments

0

If I understand you correctly you want a list like the one shown below:

  • hillary Smith
  • mary Johnson
  • John Johnson
  • John Williams
  • hillary Smith
  • ......

This code will provide a list like that,

from random import randrange

first_names=('John','mary','hillary')
last_names=('Johnson','Smith','Williams')

names = [first_names[randrange(len(first_names))] + " " + last_names[randrange(len(last_names))] for _ in range(342)]
print (names)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.