Reputation: 125
I have the following list
colors = {a, b, c}
n = 3
Where both colors and n are built dynamically. I want to create a sublist using n
and the elements of the list to get the following:
lcolors = [[a, a, a], [b, b, b], [c, c, c]]
if colors
wasn't dynamic, it was easy:
lcolors = [[a]*n, [b]*n, [c]*n]
I tried:
lcolors = colors * n
but that gave me a single list with 9 items instead of 3 sub-lists with 3 items each:
lcolors = [a, b, c, a, b, c, a, b, c]
None of the solutions offered here solve this:
Upvotes: 3
Views: 791
Reputation: 2048
If I understood correctly, you can use list comprehension:
lcolors = [[color] * n for color in colors]
Upvotes: 3
Reputation: 33179
You were really close. You just need a comprehension looping over colors
lcolors = [[x]*n for x in colors]
Upvotes: 3