On May 20, 9:58 am, Paul McGuire <[EMAIL PROTECTED]> wrote: > On May 20, 8:13 am, "John Salerno" <[EMAIL PROTECTED]> wrote: > > > > > I posted this code last night in response to another thread, and after I > > posted it I got to wondering if I had misused the list comprehension. Here's > > the two examples: > > > Example 1: > > -------------------- > > def compress(s): > > new = [] > > > for c in s: > > if c not in new: > > new.append(c) > > return ''.join(new) > > ---------------------- > > > Example 2: > > ------------------------ > > def compress(s): > > new = [] > > [new.append(c) for c in s if c not in new] > > return ''.join(new) > > -------------------------- > > > In example 1, the intention to make an in-place change is explicit, and it's > > being used as everyone expects it to be used. In example 2, however, I began > > to think this might be an abuse of list comprehensions, because I'm not > > assigning the result to anything (nor am I even using the result in any > > way). > > > What does everyone think about this? Should list comprehensions be used this > > way, or should they only be used to actually create a new list that will > > then be assigned to a variable/returned/etc.? > > Why not make the list comp the actual list you are trying to build? > > def compress(s): > seen = set() > new = [c for c in s if c not in seen and (seen.add(c) or True)] > return ''.join(new) > > or just: > > def compress(s): > seen = set() > return ''.join(c for c in s if c not in seen and (seen.add(c) or > True)) > > Using the set also gets rid of that nasty quadratic performance > thingy.
You don't need all those conditionals. A set differs from a list precisely in the fact that each element is unique. And since the function is expecting "s" to be an iterable object, it can be constructed even without a for loop: def compress(s): return list(set(s)) That does the trick. -- http://mail.python.org/mailman/listinfo/python-list