Yet another unique() function...

Paul McGuire ptmcg at austin.rr.com
Wed Feb 28 01:14:41 EST 2007


On Feb 27, 8:55 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Paul Rubin <http://phr...@NOSPAM.invalid> writes:
> > def unique(seq, keepstr=True):
> >     t = type(seq)
> >     if t==str:
> >         t = (list, ''.join)[bool(keepstr)]
> >     seen = []
> >     return t(c for c in seq if (c not in seen, seen.append(c))[0])
>
> Preferable:
>
> def unique(seq, keepstr=True):
>     t = type(seq)
>     if t==str:
>         t = (list, ''.join)[bool(keepstr)]
>     seen = []
>     return t(c for c in seq if not (c in seen or seen.append(c)))


Any reason not to use a set for the 'seen' variable?  Avoids searching
through a linear list.  The input order is preserved because the
return value is created in the generator expression, not by using the
seen variable directly.

def unique2(seq, keepstr=True):
    t = type(seq)
    if t==str:
        t = (list, ''.join)[bool(keepstr)]
    seen = set()
    return t(c for c in seq if not (c in seen or seen.add(c)))

-- Paul




More information about the Python-list mailing list