Misuse of list comprehensions?

Colin J. Williams cjw at ncf.ca
Tue May 20 20:43:01 EDT 2008


John Salerno 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.? 
> 
> 

Alternative ways of of looking at the 
problem are:

# compress.py
import sets

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

def compress1(s):
   new= []
   d= dict(zip(s, len(s)*[[]]))
   return d.keys()

def compress2(st):
   s= sets.Set(st)
   return s

if __name__ == "__main__":
   s= 'In example 1, the intention to 
make an in-place change is explicit, and 
it is'
   print (compress(s))
   print (compress1(s))
   print (compress2(s))

Results:

In exampl1,thiok-cgsd
['a', ' ', 'c', 'e', 'i', 'g', 'I', 'h', 
'k', '-', 'm', 'l', 'o', 'n', '1', 'p', 
's', 't', 'x', ',', 'd']
Set(['a', ' ', 'c', 'e', 'i', 'g', 'I', 
'h', 'k', '-', 'm', 'l', 'o', 'n', '1', 
'p', 's', 't', 'x', ',', 'd'])

Colin W.



More information about the Python-list mailing list