Endorsement of list comprehensions
Alex Martelli
aleax at aleax.it
Sat May 3 05:30:18 EDT 2003
Skip Montanaro wrote:
>
> def qsort2(lst):
> if len(lst) == 0:
> return []
> else:
> x = lst[0]
> return (qsort2([i for i in lst[1:] if i<x]) +
> [x] +
> qsort2([i for i in lst[1:] if i>=x])
>
> I know this will probably sound odd, but for me, the first time I saw the
> list comprehension expression of quicksort was the first time it was
> immediately apparent to me how quicksort worked.
Actually I prefer the version in recipe 2.11 of the (printed) Cookbook:
def qsort(L):
if len(L) <= 1: return L
return qsort([ lt for lt in L[1:] if lt < L[0] ]) + L[:1] + \
qsort([ ge for ge in L[1:] if ge >= L[0] ])
but, of course, it IS much of a muchness. I do agree that this (in
Python just as in the Haskell it was stolen from) is a little gem:-).
Alex
More information about the Python-list
mailing list