How I can multiply a=['raj' , 'rj' , 'reba'] with b=[1,2,2] (integers)to get the output as c =['raj' , 'rj' , 'rj' , 'reba' , 'reba']

Viewed 50

How I can multiply

a = ['raj' , 'rj' , 'reba']

with

b = [1,2,2]  # integers

to get the output as

c = ['raj' , 'rj' , 'rj' , 'reba' , 'reba']

My current attempt is:

from itertools import chain
a = ['raj', 'rj','reba']
b = [1, 2, 2]
for i in range(len(a)):
   c.extend(list(a[i]*b[i]))

My current output:

['r', 'a', 'j', 'r', 'j', 'r', 'j', 'r', 'e', 'b', 'a', 'r', 'e', 'b', 'a']

4 Answers
a = ['raj', 'rj','reba']
b = [1, 2, 2]

c = []
for i,j in zip(a,b):
    c.extend([i]*j)

print(c)

Output:

['raj', 'rj', 'rj', 'reba', 'reba']

zip is python's built-in function which allows you to iterate over multiple lists using a single for loop.

list.extend is function of datatype list which allows you to append element in a list

You might use map for that following way:

import itertools
a = ['raj', 'rj', 'reba']
b = [1, 2, 2]
m = map(lambda x,y:[x]*y, a, b)
lst = list(itertools.chain(*m))
print(lst)

Output:

['raj', 'rj', 'rj', 'reba', 'reba']

Note that this solution assumes that data are always correct i.e. b holds only ints and len(a) == len(b). map as its help says

 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.

In this case for each element of a I create 1-element list holding that element and multiply by corresponding value of b. Then I need to flatten it (I use itertools.chain for that) as without that I would get nested rather than flat structure.

This works:

a = ['Raj', 'Aby']
b = [1,2]
new_list = []
for i in range(len(a)):                # loop till list size
    temp_list = [a[i]] * b[i]          # ['Aby']*2 = ['Aby', 'Aby']
    new_list.extend(temp_list)         # extend() appends temp_list to new_list
print(new_list)                        # Thus ['Raj', 'Aby', 'Aby']

You can also combine temp_list = [a[i]] * b[i] new_list.extend(temp_list) to new_list.extend([a[i]] * b[i] ) . I wrote the other way for better clarity

There's even an inline version, if you prefer it:

sum([[a[k]]*b[k] for k in range(len(a))], [])

Some comments:

  • The inner list comprehension creates a list of lists, each of which contains the amounts of copies of a[k] specified by b[k]
  • The sum then essentially reduces the list of lists to a flattened version by concatenating (or adding) all lists together. The second argument in the sum indicates where it starts from - an empty list (the argument is actualy needed, since the default is 0 and a list cannot be added to an Integer).
Related