Re: Return different values of a list
- To: mathgroup at smc.vnet.net
- Subject: [mg49435] Re: [mg49425] Return different values of a list
- From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
- Date: Tue, 20 Jul 2004 07:53:25 -0400 (EDT)
- References: <200407191146.HAA09125@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
[Numerous people posted similar messages about Union after this one. Those will not be posted. -- Moderator] On 19 Jul 2004, at 20:46, Dr. Wolfgang Hintze wrote: > *This message was transferred with a trial version of CommuniGate(tm) > Pro* > Given a list containing repeating values like e.g. > > x={a,b,c,a,c} > > I would like to produce a list containing each element just once > i.e. > > y={a,b,c} > > What is the easiest way to accomplish this? > > Wolfgang > > This is a classic question on this list. The "easiest" way is to take Union: Union[{a,b,c,a,c}] {a,b,c} but that sorts the elements. So if you do not want them to be sorted than there are lots of possibilities, whose merits depend on the nature of your list. The classic answer is Carl Woll's OrderedUnion OrderedUnion[li_]:=Block[{i,Sequence}, i[n_]:=(i[n]=Sequence[];n);i/@li] Another approach (with a different evaluation order) uses Hold: OrderedUnionH[li_] := ReleaseHold[Block[{i}, i[n_] := (i[n] = Hold[]; n); i /@ li]] Other approaches will be faster for numerical lists. It really depends on what sort of problem you want to use it on. Andrzej Kozlowski Chiba, Japan http://www.mimuw.edu.pl/~akoz/
- References:
- Return different values of a list
- From: "Dr. Wolfgang Hintze" <weh@snafu.de>
- Return different values of a list