is this pythonic?

alex23 wuwei23 at gmail.com
Wed Jan 21 12:41:02 EST 2009


On Jan 22, 3:27 am, MRAB <goo... at mrabarnett.plus.com> wrote:
> FYI, you shouldn't modify a list you're iterating over.

But I'm not. I'm building a new list and binding it to the same name
as the original, which works perfectly fine (unless I'm missing
something):

>>> l = range(100)
>>> l = [d for d in l if not d % 5]
>>> l
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85,
90, 95]

> The for-loop was removing the item where there's a match, so the list
> comprehension in this case should keep the item where there _isn't_ a match:
>
> l = [d for d in l if d['title'] != 'ti']

Now that's a mistake. Cheers for the catch.



More information about the Python-list mailing list