pythonlistfor-looplist-manipulation

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:

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']