Misuse of list comprehensions?
Ian Kelly
ian.g.kelly at gmail.com
Tue May 27 23:46:58 EDT 2008
On Tue, May 27, 2008 at 8:08 PM, Gabriel Genellina
<gagsl-py2 at yahoo.com.ar> wrote:
> En Tue, 27 May 2008 14:43:52 -0300, Ian Kelly <ian.g.kelly at gmail.com>
> escribió:
>
>> 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)
>
> filter returns a newly created list, so this code is as wasteful as a list
> comprehension (and harder to read).
Here it returns a newly created *empty* list, which is not nearly as
wasteful as one that's linear in the size of the input. I'll grant
you the second point, though. I very much doubt that I would ever
actually use this myself. I was just curious what others would think
of it.
More information about the Python-list
mailing list