Search code examples
pythonlistloopsnestedsubtraction

How to subtract all elements in list from one element in another list?


I have a problem with mathematically subtracting all elements of one list against one element of another list. This is what I need:

>>>list1 = [ a, b, c]
>>>list2 = [ d, e, f]    

result = [ d-a, e-a, f-a, d-b, e-b, f-b, d-c, e-c, f-c]

I tried with a nested loop for but it doesn' t work out just fine:

 subtr = [] 
 for i in list1:
    for j in list2:
       subtr.append(j - i)

If someone could please help I would be very thankful!


Solution

  • Here is a simple solution:

    list1 = [1, 2, 3]
    list2 = [10, 20, 30]
    
    result = [x-y for y in list1 for x in list2]
    

    Result:

    [9, 19, 29, 8, 18, 28, 7, 17, 27]