3

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 2

3

If I understood correctly, you can use list comprehension:

lcolors = [[color] * n for color in colors]
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.