Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have lists like

list1={1, 1, 2, 3}; list2={3, 1, 4}; list3={};

I want to find the intersection of all list. I tried the following way, but it's not working.

Intersection[Cases[{list1, list2,list3}, Except[{}]]]

I want output like this

{1, 3} 

Fell free, if you want to edit my question.

share|improve this question
1  
If list3=={}, the intersection will be {} .... –  belisarius Apr 11 '13 at 13:27
    
Try Intersection @@ Cases[...] @belisarius I think subbu wants to exclude empty sets from the list of intersected sets. –  István Zachar Apr 11 '13 at 13:27
    
also: Intersection @@ DeleteCases[{list1, list2, list3}, {}] –  Yves Klett Apr 11 '13 at 13:30
    
@IstvánZachar you are right,what you understood –  subbu Apr 11 '13 at 13:30
    
@subbu Cases, like many functions, returns a single list. But Intersection wants a set of lists to compare. So your code wasn't 'reaching far enough' into the results of Cases to give you the answer you want. If you haven't seen it already, Leonid's book is worth reading. –  cormullion Apr 12 '13 at 15:39

3 Answers 3

up vote 3 down vote accepted

Here's a different way:

list1 = {1, 1, 2, 3}; list2 = {3, 1, 4}; list3 = {};
Intersection @@ DeleteCases[{list1, list2, list3}, {}]

Which gives:

{1,3}
share|improve this answer

Try like this,

list1 = {1, 1, 2, 3}; list2 = {3, 1, 4}; list3 = {};
Intersection[Sequence @@ Cases[{list1, list2, list3}, Except[{}]]]
share|improve this answer

If you want the elements existing in more than one list you could try:

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

list2 = {3, 1, 4};

list3 = {4};
Union @@ Intersection @@@ Subsets[{list1, list2, list3}, {2}]

(* {1, 3, 4} *)

edit With an empty list3

list1 = {1, 1, 2, 3};
list2 = {3, 1, 4};
list3 = {};
Union @@ Intersection @@@ Subsets[{list1, list2, list3}, {2}]
(* {1,3} *)
share|improve this answer
    
sorry,my list3 is empty like {} –  subbu Apr 11 '13 at 13:32
    
@subbu Try it with list3 = {} then –  belisarius Apr 11 '13 at 13:32
    
If I assign list3={},I will get output is like {}.But I want output like {1,3}.indirectly I want to exclude empty sets from the list of intersects sets. –  subbu Apr 11 '13 at 13:37
    
@subbu See edit –  belisarius Apr 11 '13 at 13:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.