Question

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.

Was it helpful?

Solution

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']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top