List comprehension

Martin von Loewis loewis at informatik.hu-berlin.de
Tue Sep 5 12:21:38 EDT 2000


Roy Katz <katz at Glue.umd.edu> writes:

> Does anyone have more examples of how and when to use this (as in,
> actual code)?  I'm itching to try and find ways to optimize my programs
> with it. 

I took a piece of Python standard library randomly, calendar.py, and
looked for for statements. The second one in the file is

def weekheader(width):
    """Return a header for a week."""
    if width >= 9:
        names = day_name
    else:
        names = day_abbr
    days = []
    for i in range(_firstweekday, _firstweekday + 7):
        days.append(_center(names[i%7][:width], width))
    return ' '.join(days)

which, I believe, could become

def weekheader(width):
    """Return a header for a week."""
    if width >= 9:
        names = day_name
    else:
        names = day_abbr
    days = [_center(names[i%7][:width], width)  \
            for i in range(_firstweekday, _firstweekday + 7)]
    return ' '.join(days)

For another example, 

    def unpack_farray(self, n, unpack_item):
        list = []
        for i in range(n):
            list.append(unpack_item())
        return list

from xdrlib could become

    def unpack_farray(self, n, unpack_item):
        return [unpack_item() for i in range(n)]

Regards,
Martin




More information about the Python-list mailing list