Reputation: 3660
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))
Upvotes: 0
Views: 58
Reputation: 714
If I understand you correctly you want a list like the one shown below:
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)
Upvotes: 0
Reputation: 22776
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', ...]
Upvotes: 2