How to multiply a zipped list’s items with eachother?

  lambda, list-comprehension, python, python-3.x

I’m doing an exercise where I create a function that receives two lists and returns the multiplications of the items at the same indices in a separate single list. Example:

transform("1 5 3", "2 6 -1")
#should return
[2, 30, -3]

To be clear, the program takes the items at index 1, 2 and 3 and multiplies them like this:

(1 * 2), (5 * 6), (3 * -1)

Now, the problem I face is that it is a must to use zip() function in the program, which I have not properly used yet.

I have made a program that does the general task successfully, but I can’t figure out a solution that would use a zipped list. Could anyone help me with this? I have an idea that I could use the zipped list "q" that I have created within the map() function, but I don’t know how.

Here is my program:

def transform(s1, s2):
    i = 0

    s = s1.split(' ')
    d = s2.split(' ')

    while i < len(s):
        try:
            s[i] = int(s[i])
            d[i] = int(d[i])
            i += 1
        except ValueError:
            break

    print(s, d)

    q = list(zip(s, d))
    print(q)

    final = list(map(lambda x, y: x * y, s, d))

    return final

def main():
    print(transform("1 5 3", "2 6 -1"))

if __name__ == "__main__":
    main()

Thank you in advance to anyone that helps!

Source: Python Questions

LEAVE A COMMENT