Misuse of list comprehensions?

MRAB google at mrabarnett.plus.com
Tue May 27 18:15:47 EDT 2008


On May 27, 6:43 pm, "Ian Kelly" <ian.g.ke... at gmail.com> wrote:
> On Tue, May 20, 2008 at 11:19 AM, John Salerno <johnj... at nospamgmail.com> wrote:
> > "Diez B. Roggisch" <de... at nospam.web.de> wrote in message
> >news:69g605F2v4102U2 at mid.uni-berlin.de...
> >> After being corrected about missing the construction of a None-containing
> >> list, one needs of course to think about the waste of resources, as a
> >> possible result-list is created in any case.
>
> > Yeah, I was already aware of the list of Nones, which is why I asked. Simply
> > typing the list comprehension without an assignment just *looked* wrong,
> > too.
>
> It sounds like the wasteful list creation is the biggest objection to
> using a list comprehension.  I'm curious what people think of this
> alternative, which avoids populating the list by using a generator
> expression instead (apart from the fact that this is still quadratic,
> which I'm aware of).
>
> def compress(s):
>    new = []
>    filter(None, (new.append(c) for c in s if c not in new))
>    return ''.join(new)

It could be shorter:

def compress(s):
    new = []
    return filter(None, (new.append(c) for c in s if c not in new)) or
''.join(new)

:-)



More information about the Python-list mailing list