modifying mutable list elements in a for loop

Larry Bates lbates at swamisoft.com
Wed May 26 10:04:16 EDT 2004


If you write this as a list comprehension it "seems"
more safe (and clear to me at least):

a = [[1,2], [3,4], [5,6], [7,8]]
a = [x+[10] for x in a]

Larry Bates
Syscon, Inc.

"Peter Ballard" <pballard at ozemail.com.au> wrote in message
news:9d5509fa.0405260439.175797e at posting.google.com...
> Whew. I hope that title is descriptive!
>
> Hi all,
>
> The python tutorial tells me "It is not safe to modify the sequence
> being iterated over in the loop". But what if my list elements are
> mutable, such as lists or objects, e.g.
>
> a = [[1,2], [3,4], [5,6], [7,8]]
> for coord in a:
>      coord.append(10)
> print str(a)
>
> When I tried it, it gave the "expected" answer, i.e.
>
> [[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]]
>
> It worked, but is it safe? I can't see why it wouldn't be, but
> technically I have broken the rules because I have modified the
> sequence which is being looped over.
>
> [It seems to me that the list elements are pointers (in C-speak), so I
> can safely modify the data they are pointing to, because I am not
> modifying the list elements themselves. Or is that an implementation
> detail (i.e. not safe)?]
>
> Actually the more I think about it the more I think it must be OK,
> because how else can one perform an operation on a list of objects?
> But that phrase "It is not safe to modify the sequence being iterated
> over in the loop" in the tutorial has me slightly worried.
>
> --
> Regards,
>
> Peter Ballard
> Adelaide, AUSTRALIA
> pballard at ozemail.com.au
> http://members.ozemail.com.au/~pballard/





More information about the Python-list mailing list