Search code examples
python-2.7listsage

Combine two lists of different length python


I have this code:

L = [1, x, x**2]
L2 = [1, 2*x]
def my_mul(x,y):
    if x == None: return y
    if y == None: return x
    return x*y
map(my_mul, L, L2)

This produces what I want, which is a element-wise product of L and L2.

[1, 2*x^2, x^2]

But is there a more pythonic way of achieving this?

Concretely, can I do this without defining my own function?


Solution

  • The code below should achieve what you need

    import itertools
    import operator
    
    l1 = [1, 2, 3]
    l2 = [1, 2, 3, 4]
    
    list(itertools.starmap(operator.mul, itertools.zip_longest(l1, l2, fillvalue=1)))
    # result [1, 3, 9, 4]
    

    Explanation

    zip_longest will zip and fill missing values from shorter list:

    itertools.zip_longest(l1, l2, fillvalue=1)
    [(1, 1), (2, 2), (3, 3), (1, 4)]
    

    starmap will apply multiplication operator to every integer pair