Is this a safe thing to do?
logistix at cathoderaymission.net
logistix at cathoderaymission.net
Thu Oct 9 13:48:24 EDT 2003
phil_nospam_schmidt at yahoo.com (Phil Schmidt) wrote in message news:<221e7b06.0310090440.727cf10f at posting.google.com>...
> The following example works fine (Python 2.3), but is it always safe
> to modify a list that is being iterated in a loop, regardless of the
> actual contents of the list x? If not, what's a better (safe) way to
> do it?
>
> Thanks!
>
>
> >>> x=[{'f':9},{'f':1},{1:3,'f':9},{'f':3}]
> >>> for t in x:
> if t['f'] == 9:
> x.remove(t)
>
>
> >>> x
> [{'f': 1}, {'f': 3}]
This is the perfect place to use a list comprehension:
>>> x=[{'f':9},{'f':1},{1:3,'f':9},{'f':3}]
>>> x = [t for t in x if t['f'] != 9]
>>> x
[{'f': 1}, {'f': 3}]
>>>
More information about the Python-list
mailing list