Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python list comprehension : build a list from 2 lists

This code

colors = ["#F1A141", "#52D987", "#12A3FF", "#FF3F94", "#564DA6"]
skills = [3, 4, 4, 2, 3]
palette = [(item for i in range(skills[index])) for (index, item) in enumerate(colors)]

returns no error but buggy list items

[<generator object <listcomp>.<genexpr> at 0x7f302eac9650>, <generator object <listcomp>.<genexpr> at 0x7f302eac9550>, ... ]

Where’s my mistake ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit : the expected output is a list with 3 "#F1A141" items followed by 4 "#52D987" items, etc.

>Solution :

This is a generator expression: (item for i in range(skills[index]) if you want a list of lists, you need to use [] inside the comprehension.

Given your desired output, it might be simpler to zip the two lists and avoid the range. Then nest the comprehension to flatten it:

colors = ["#F1A141", "#52D987", "#12A3FF", "#FF3F94", "#564DA6"]
skills = [3, 4, 4, 2, 3]

[c for color, n in zip(colors, skills) for c in [color] * n]

Produces:

['#F1A141',
 '#F1A141',
 '#F1A141',
 '#52D987',
 '#52D987',
 '#52D987',
 '#52D987',
 '#12A3FF',
 '#12A3FF',
 '#12A3FF',
 '#12A3FF',
 '#FF3F94',
 '#FF3F94',
 '#564DA6',
 '#564DA6',
 '#564DA6']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading