unique-ifying a list
Simon Forman
sajmikins at gmail.com
Sun Aug 9 17:02:51 EDT 2009
On Aug 7, 4:53 pm, kj <no.em... at please.post> wrote:
> Suppose that x is some list. To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
> x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
> seen = set()
> ret = []
> for i in items:
> if not i in seen:
> ret.append(i)
> seen.add(i)
> return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions. Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?
>
> TIA!
>
> kynn
Unique items in a list, in the same order as in the list:
x = sorted(set(x), key=x.index)
;]
More information about the Python-list
mailing list