Scott Woodhall
Scott Woodhall

Reputation: 305

Duplicating Items in list based on value of a different list

list1 = ['Name1', 'Name2', 'Name3']
list2 = [1, 3, 2]

desired result:

['Name1', 'Name2', 'Name2', 'Name2', 'Name3', 'Name3']

Looking to duplicate items in a list based on the corresponding element position of a different list. Any help would be great, thank you.

Upvotes: 0

Views: 34

Answers (2)

no comment
no comment

Reputation: 10165

With chain and repeat from itertools:

res = list(chain.from_iterable(map(repeat, list1, list2)))

Short version:

res = [*chain(*map(repeat, list1, list2))]

Try it online!

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

Use the following list comprehension + zip:

list1 = ['Name1', 'Name2', 'Name3']
list2 = [1, 3, 2]

res = [e1 for e1, e2 in zip(list1, list2) for _ in range(e2)]
print(res)

Output

['Name1', 'Name2', 'Name2', 'Name2', 'Name3', 'Name3']

Upvotes: 1

Related Questions