Misuse of list comprehensions?

s0suk3 at gmail.com s0suk3 at gmail.com
Tue May 20 14:01:24 EDT 2008


On May 20, 12:22 pm, "John Salerno" <johnj... at NOSPAMgmail.com> wrote:
> "Paul McGuire" <pt... at austin.rr.com> wrote in message
>
> news:b56a93ee-b177-44fb-927a-1e204f491639 at t54g2000hsg.googlegroups.com...
> On May 20, 10:50 am, s0s... at gmail.com wrote:
>
> > def compress(s):
> > return list(set(s))
>
> > That does the trick.
>
> Wow, I just *knew* there had to be some built-in function that would make
> this problem trivial! :)
>
> Only if order does not need to be maintained.  list(set(s)) will not
> necessarily keep the unique characters in the order they are seen.
> We'll have to check with the OP to see if this is important (I just
> assumed that it was because of the use of list comps).
>
> Good point. For me it doesn't matter because it wasn't my problem
> originally. I just had a question about the list comp. But if order matters,
> then I guess set doesn't work?

Yeah, it doesn't work. I didn't know that detail about sets until now
(like dicts, you can't expect the order to remain the same). I also
forgot that you were joining the list, so the return statement would
have looked like "return ''.join(set(s))", but you have to go with the
list comprehension if you want it to keep the same order.



More information about the Python-list mailing list