Compress a string

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Tue May 20 02:55:19 EDT 2008


On Tue, 20 May 2008 00:38:57 -0400, John Salerno wrote:

> def compress(s):
>     new = []
> 
>     for c in s:
>         if c not in new:
>             new.append(c)
>     return ''.join(new)
> 
> 
> No, wait! I can do better!
> 
> def compress(s):
>     new = []
>     [new.append(c) for c in s if c not in new] return ''.join(new)
> 
> Wow, list comprehensions are cool.

And it's a misuse of list comprehension here IMHO because they are meant to
build lists, not to cram a ``for``/``if`` loop into a one liner.  You are
building a list full of `None` objects, just to throw it away.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list