Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2002

[Date Index] [Thread Index] [Author Index]

Search the Archive

RE: Keeping order with Union

  • To: mathgroup at
  • Subject: [mg32611] RE: [mg32590] Keeping order with Union
  • From: "David Park" <djmp at>
  • Date: Thu, 31 Jan 2002 01:45:42 -0500 (EST)
  • Sender: owner-wri-mathgroup at


If your list is composed of integers or exact expressions, then there is the
very efficient and clever routine that Carl Woll put forth a year or so ago
on MathGroup.

RemoveRepeats[x_] :=
    i[n_] := (i[n] = Sequence[]; n);
    i /@ x]

list = Array[Random[Integer, {0, 9}] &, 100]

{1, 9, 0, 7, 6, 4, 3, 2, 5, 8}

Here is an alternative method, much slower, but it can be used on
approximate expressions if you adjust the SameTest to something appropriate
for the specific case.

list2 = Transpose[{Range[Length[list]], list}];
list2 = Union[list2, SameTest ->
     (#1[[2]] == #2[[2]] & )];
Last /@ list2

When I ran on a list of 100000 integers, the Woll routine took 0.39 seconds,
and the second routine took 6.42 seconds.

David Park
djmp at

> From: Dave Snead [mailto:dsnead6 at]
To: mathgroup at
> I'd like a function that throws out duplicate entries in a list and keeps
> the
> original list order.  (when it sees 2 equal entries it throws out the one
> that is later in the list).   I'd use Union, but it sometimes changes the
> order of the elements in the list.  What's the tersest way to do this?
> Thanks in advance,
> Dave Snead

  • Prev by Date: Re: Gross Bug in Simplify
  • Next by Date: RE: another integral problem
  • Previous by thread: Re: Keeping order with Union
  • Next by thread: How to get rid of this format