When is List Comprehension inappropriate?

Paul McGuire ptmcg at austin.rr.com
Mon Mar 19 11:43:33 EDT 2007


On Mar 19, 9:41 am, "Ben" <bensher... at gmail.com> wrote:
> even = []
> for x in range(0,width,2):
>     for y in range(0,height,2):
>         color = im.getpixel((x,y))
>         even.append(((x,y), color))
>
> versus list comprehension:
>
> even2 = [((x,y), im.getpixel((x,y))) for x in range(0,width,2) for y
> in range(0,height,2)]
>

To simplify access to individual pixels, you can make even2 into a
dict using:

  even2asDict = dict(even2)

and then you can directly get the pixel in the 4th row, 5th column
(zero-based) as:

  even2asDict[(4,5)]

If you really want something more like a 2-D array, then create a list
comp of lists, as in:

  even2 = [ [im.getpixel((x,y)) for x in range(0,width,2) ]
             for y in range(0,height,2) ]

which allows you to use list indexing to get individual pixel values,
as in:

  even2[4][5]

to get the same pixel as above.

-- Paul




More information about the Python-list mailing list