3

Consider the following:

list={{a,b,c},{c,d,e},{d,e,f},...{x_,y_,z_}};

I would like to apply Union on the elements of the list in the following way

Union[{a,b,c},{c,d,e},{d,e,f},...{x_,y_,z_}];

The problem Union[list] does not return the desired result when applied on list. Please consider the following example:

list={{10,2,3},{2,3,4},{2,3,50}};
Union[list]

The same problem occures with Intersection.

(* Out={{10,2,3},{2,3,4},{2,3,50}} *)

Instead of

Union[{10,2,3},{2,3,4},{2,3,50}]
(* Out={2,3,4,10,50} *)
rm -rf
  • 88,781
  • 21
  • 293
  • 472
John
  • 4,361
  • 1
  • 26
  • 41

3 Answers3

9

You're looking for Apply

Mathematica graphics

Apply[Union, list]

which can be written in short form as

Union@@list
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Rojo
  • 42,601
  • 7
  • 96
  • 188
6

Union eliminates duplicate elements in a list, or duplicate sublists in a list of lists.

In[9]:= list = {{a, a, a}, {a, a, a}, {d, e, f}};
        Union[list]

Out[10]= {{a, a, a}, {d, e, f}} 

In your example,

list={{10,2,3},{2,3,4},{2,3,50}};                      
Union[list]  

even though parts of the sublists are the same, no sublist was a complete duplicate of any other sublist. So there was nothing for Union to do.

István Zachar
  • 47,032
  • 20
  • 143
  • 291
Nico
  • 61
  • 1
  • +1 for the explanation why the OP's example does not behave as expected. – István Zachar Jun 01 '12 at 09:46
  • Welcome to Mathematica.SE and thanks for taking the time to explain this. Please consider registering your account so your reputation score will be preserved and you can access to more features of the site. – Szabolcs Jun 01 '12 at 09:55
5

Just stir things up, you can also do the following:

Union[Sequence@@list]

It uses the same function referenced (Map), but makes forces the problem to look like you were expecting:

Union[{a,b,c},{c,d,e},{d,e,f},...{x_,y_,z_}];
tkott
  • 4,939
  • 25
  • 44