Search code examples
pythonlistnested-loops

How to multiply the elements of two lists with each other in python?


You have to create an N-string. An N-string is a string created using two lists. The first list consists of strings. The second list consists of integer values. These two lists are of same length. Each string from the first list has to be repeated for m-times where m is the respective integer value from the second list. The resulting string is the concatenation of all these repeated strings.

def n_strings(names, numbers):
    nString = []
    for name in names:
        for number in numbers:
            n = name * number
            nString.append(n)
    return nString
names = ["Neymar","Abir","Samuel"]
numbers = [1,2,3]

print(n_strings(names,numbers))

Solution

  • Iterate over the length of one array.

    def n_strings(names, numbers):
        nString = ""
        for i in range(0,len(names)):
            n = names[i] * numbers[i]
            nString += n
        return nString
    names = ["Neymar","Abir","Samuel"]
    numbers = [1,2,3]
    
    print(n_strings(names,numbers))