luca giovanni voglino
luca giovanni voglino

Reputation: 29

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!

Upvotes: 0

Views: 1266

Answers (2)

Michael Szczesny
Michael Szczesny

Reputation: 5036

With list comprehensions and example values

list1 = [ 10, 20, 30]
list2 = [ 1, 2, 3] 

[y - x for x in list1 for y in list2]

Out:

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

Your code does the same. You can test it with example values

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

Out:

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

Upvotes: 4

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

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]

Upvotes: 2

Related Questions