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

Multiplying a list of integer with a list of string

Suppose there are two lists:

l1 = [2,2,3]
l2 = ['a','b','c']

I wonder how one finds the product of the two such that the output would be:

#output: ['a','a','b','b','c','c','c']

if I do:

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

l3 = []
for i in l2:
    for j in l1:
        l3.append(i)

I get:

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

which is wrong, I wonder where am I making the mistake?

>Solution :

The loop for j in l1: will iterate 3 times every time (because you have 3 items in list l1).

Try:

out = [b for a, b in zip(l1, l2) for _ in range(a)]
print(out)

Prints:

['a', 'a', 'b', 'b', 'c', 'c', 'c']
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