Intersect
Intersect
Intersect[ list1, list2, ... ] returns the elements of the first list that also occur in all other lists.
Usages
Intersect[ list1, list2 ]
Intersect[ list1, list2 ] returns a new list with the elements of list1 that also occur in list2. The elements keep their order from list1.
| Example | in | out |
|---|---|---|
a and b occur in both lists. |
Intersect[ {a,b,g}, {a,b,c,d,e,a} ] |
{a, b} |
a occurs twice in both lists, so it is kept twice. |
Intersect[ {a,b,g,a}, {a,c,a} ] |
{a, a} |
a occurs only once in the second list, so it is kept once. |
Intersect[ {a,b,g,a}, {a,c} ] |
{a} |
| Lists stored in script variables. | x := {a,b,c} |
z = {b, c} |
Intersect[ list1, list2, list3, ... ]
With more than two lists, the result contains the elements of list1 that occur in every other list.
| Example | in | out |
|---|---|---|
Only a occurs in all three lists. |
Intersect[ {a,b,g,a}, {a,b,c,d,e,a}, {g,d,f,a} ] |
{a} |
Details
- Duplicates are counted separately: an element is kept as many times as it occurs in every list. Each element of
list2can match only one element oflist1. - 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.4and12/5do not match. Numbers with a limited precision, such asPrecisionConstant[3.14,2], match a value within that precision. - Empty lists: if any of the lists is empty, the result is
{}. - Single list:
Intersect[ {a,b} ]returns{a, b}.
| Example | in | out |
|---|---|---|
1+x matches x+1. |
Intersect[ {x+1, 3}, {1+x} ] |
{x+1} |
12/5 does not match 2.4. |
Intersect[ {2.4, 3}, {12/5, 3} ] |
{3} |
| Invalid input | Result |
|---|---|
Intersect[ {a,b}, b ] |
Left unevaluated: the result is Intersect[ {a,b}, b ] itself. All arguments must be lists. |
See also: IntersectI, Difference, Tally