Endorsement of list comprehensions

Willi Kappler grandor at gmx.de
Fri May 2 14:57:37 EDT 2003


Michael Chermside <mcherm at mcherm.com> wrote in message 
> YES! Exactly!
> 
> This is a feature called "list comprehensions", and it works just like
> you describe. You type out:
> 
>     [ func_using_var for var in some_list if condition_using_var ]
> 
> and Python makes that into the following loop:
> 
>     aList = []
>     for var in some_list:
>         if condition_using_var:
>             aList.append( func_using_var )
>     return aList
> 
> (except, of course, that there's no "aList" variable... python just
> uses the list that would be generated that way).
> 
> The original idea comes from "Haskell", another cool programming
> language, and the strongest argument I've EVER heard for why this
> is a good feature is the little "stream-of-consciousness" description
> you just gave which seems to show that as a new-to-python programmer,
> it took you only a few moments to figure it out (correctly!) on your
> own!
> 
> Thanks for endorsing one of my favorite Python features!
> 
> -- Michael Chermside

A very good example of this feature is the quicksort algorithm:

in haskell ( as mentioned above, a cool functional programming
language ):

qsort []     = []
qsort (x:xs) = qsort elts_lt_x ++ [x] ++ qsort elts_greq_x
                 where
                   elts_lt_x   = [y | y <- xs, y < x]
                   elts_greq_x = [y | y <- xs, y >= x]


and in python:

#!/usr/bin/python

def qsort(lst):
	if len(lst) == 0:
		return []
	else:
		x = lst[0]
		return qsort(filter(lambda i: i<x, lst[1:])) + [x] +
qsort(filter(lambda i: i>=x, lst[1:]))

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])

lst = [ 5, 7, 3, 2, 9, 1, 4, 5, 10, 34, 21, 4, 8, 3, 1, 9, 4, 11 ]
print lst
print qsort(lst)
print qsort2(lst)

As you see, I found two possible ways of doing it. Maybe there is an
other one...

Willi




More information about the Python-list mailing list