Python Create a list of sublists from a list

Viewed 442

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:

2 Answers

You were really close. You just need a comprehension looping over colors

lcolors = [[x]*n for x in colors]

If I understood correctly, you can use list comprehension:

lcolors = [[color] * n for color in colors]
Related