modifying mutable list elements in a for loop

Peter Ballard pballard at ozemail.com.au
Wed May 26 08:39:07 EDT 2004


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