# one list minus another

I have one list like this {{1, 3}, {2, 5}} and another like this {1,2}, so I want to do first list minus second so that result will be {{1, 2}, {2, 3}}. How can I do this?

Try MapThread

list1={{1, 3}, {2, 5}};list2={1,2};


which instantly gives you

{{1,2},{2,3}}


Study the documentation and see if you can figure out how this works. It takes corresponding pairs of items from each list and does a function to them, in this case doing your subtraction on part of the first list.

If this & and # stuff is confusing then an equivalent solution that perhaps makes the function more understandable is

list1={{1, 3}, {2, 5}};list2={1,2};
f[v1_,v2_]:=v1-{0,v2};


That will do

{1,3}-{0,1}=={1,2}


and then do

{2,5}-{0,2}=={2,3}


{{1,2},{2,3}}


A completely different way of doing this is to turn your two lists into exactly the same shape and size matricies and then just subtract the two matricies.

list1-Map[{0,#}&,list2]


which gives you

{{1,2},{2,3}}


There are many approaches. These also works.

list1 = {{1, 3}, {2, 5}};
list2 = {1, 2};

Transpose@(Transpose@list1 - {{0, 0}, list2})
(* {{1, 2}, {2, 3}} *)


or

list1 - Transpose@{{0, 0}, list2}


I didn't at first understand the problem statement. We are subtracting the second list from the second element of the first list.

With that understanding, here is another possibility:

Transpose[{list1[[;; , 1]], list1[[;; , -1]] - list2}]


This method is using "spans" to pair the first elements of list1 with the second (last) element of list1 minus list2.

l1 = {{1, 3}, {2, 5}};
l2 = {1, 2};


SubsetMap[# - l2 &, l1, {All, 2}]

l3 = l1; l3[[All, 2]] -= l2; l3