unique-ifying a list

kj no.email at please.post
Fri Aug 7 16:53:10 EDT 2009



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



More information about the Python-list mailing list