Jorge Gandara Jorge Gandara - 21 days ago 5
Python Question

How do I multiply one list by another in every possible combination?

For example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]


Wanted result:

NewList = [4, 5, 6, 8, 10, 12, 12, 15, 18]

Answer

Three possible approaches:

  1. Readable

    new_list = []
    for a in list1:
        for b in list2:
             new_list.append(a * b)
    

    This makes it very clear what's going on, but requires four lines and repeated calls to new_list.append(), which is slightly inefficient.

  2. Concise

    new_list = [a * b for a in list1 for b in list2]
    

    This is very compact, but for many people it takes a moment or two to remember whether the nesting of multiple-for list comprehensions goes left-to-right or right-to-left.

  3. Lazy

    from itertools import product
    
    new_list = [a * b for a, b in product(list1, list2)]
    

    This will work correctly even if list1 and list2 are generators or other one-shot, lazily-evaluated iterables, e.g.

    >>> from itertools import count, islice
    >>> list1 = islice(count(1), 3)
    >>> list2 = islice(count(4), 3)
    >>> [a * b for a, b in product(list1, list2)]
    [4, 5, 6, 8, 10, 12, 12, 15, 18]
    

    ... which won't work with the first two approaches.

Note that I've used new_list rather than NewList in these examples, which is the conventional way to name variables in Python.