When is List Comprehension inappropriate?
paddy3118 at googlemail.com
Wed Mar 21 08:23:44 CET 2007
On Mar 19, 2:41 pm, "Ben" <bensher... at gmail.com> wrote:
> I have recently learned how list comprehension works and am finding it
> extremely cool. I am worried, however, that I may be stuffing it into
> places that it does not belong.
> What's the most "pythony" way to do this:
> 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)]
> Is there a computational difference in creating a blank list and
> appending to it versus doing a list comprehension? Are there
> advantages to it outside of short and pretty code?
> Feel free to tell me a different way to do this, as well.
I have found that I have gone too far when I used listcomps for their
sideeffects rather than wanting the list produced, for example the
second listcomp below is an expression as statement I don't want the
list produced - just the effect on data.
>>> # some random ranges
>>> data = [range(random.randrange(3,7)) for x in range(4)]
>>> # but I want each range jumbled
>>> [ random.shuffle(d) for d in data]
[None, None, None, None]
[[2, 0, 3, 1], [0, 2, 1], [3, 4, 1, 0, 2], [2, 1, 0, 3]]
(I do know how to re-write it).
More information about the Python-list