Endorsement of list comprehensions

Michael Chermside mcherm at mcherm.com
Tue Apr 29 17:13:32 EDT 2003


Carsten Gehling writes:
> Okay I understand everyting except this contruct:
> 
> keys = [d[0] for d in cursor.description]
> 
> Let me guess: it loops through cursor.description (obvious), for each of the
> items (which are tuples) it "outputs" element 0. The output is then
> automatically formatted in a way, that conforms to the list creation syntax.
> 
> Or something like that. Kind of neat - haven't seen that in any other
> language, that I've used.

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






More information about the Python-list mailing list