-2

What I have:

names = ["Bob", "Dora", "Kelly"]
numbers = [5, 3, 2]

What I need:

list1 = ["Bob", "Bob", "Bob", "Bob", "Bob", "Dora", "Dora", "Dora", "Kelly", "Kelly"]

Such that their names are appended to a new list times i number of times as indicated by my numbers list.

1 Answer 1

5

Use zip() and a list comprehension:

[name for name, count in zip(names, numbers) for _ in range(count)]

zip() pairs up each name with each number, the list comprehension uses a nested set of for loops to repeat name the right number of times.

Demo:

>>> names = ["Bob", "Dora", "Kelly"]
>>> numbers = [5, 3, 2]
>>> [name for name, count in zip(names, numbers) for _ in range(count)]
['Bob', 'Bob', 'Bob', 'Bob', 'Bob', 'Dora', 'Dora', 'Dora', 'Kelly', 'Kelly']

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.