Difference

Difference

Difference[ list1, list2, ... ] returns a copy of the first list, with the elements of the other lists removed.

Usages

Difference[ list1, list2 ]

Difference[ list1, list2 ] returns a new list with the elements of list1, where each element of list2 removes one matching element from list1. The remaining elements keep their order from list1.

Example in out
Remove g and one a. The second a remains. Difference[ {a,b,g,a}, {g,a} ] {b, a}
Both a's are removed, because list2 contains a twice. Elements of list2 that are not in list1 are ignored. Difference[ {a,b,g,a}, {a,b,c,d,e,a} ] {g}
Lists stored in script variables. x := {3, 8, 5, 8}
y := Difference[x, {8}]
y = {3, 5, 8}

Difference[ list1, list2, list3, ... ]

With more than two lists, the elements of list2, list3, ... are all removed from list1.

Example in out
Remove 2, 4 and 5. Difference[ {1,2,3,4,5,6}, {2,4}, {5} ] {1, 3, 6}
Details
  • Duplicates are counted separately: an element of list2 removes only one matching element of list1, working from left to right.
  • Equal elements: elements match if they are the same mathematical expression, regardless of the order of terms or factors. Numbers must have the same form: 2.4 and 12/5 do not match. Numbers with a limited precision, such as PrecisionConstant[3.14,2], match a value within that precision.
  • Empty lists: Difference[ {1,2,3}, {} ] returns {1, 2, 3}. When all elements are removed, the result is {}.
  • Single list: Difference[ {a,b} ] returns {a, b}.
Example in out
1+x matches x+1. Difference[ {x+1, 2y, 3}, {1+x} ] {2y, 3}
12/5 does not match 2.4. Difference[ {2.4, 12/5, 3}, {12/5} ] {2.4, 3}
Invalid input Result
Difference[ {a,b}, a ] Left unevaluated: the result is Difference[ {a,b}, a ] itself. All arguments must be lists.

See also: DifferenceI, Intersect, RemoveI