modifying mutable list elements in a for loop

Shalabh Chaturvedi shalabh at cafepy.com
Wed May 26 09:16:24 EDT 2004


Peter Ballard wrote:
> 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.

You're fine. You didn't modify the sequence a, but other objects which 
happened to be in the sequence. What the tutorial warns you against is 
doing something like a.append([]) or a.pop() in your loop. Then you'd be 
modifying the sequence itself.

--
Shalabh





More information about the Python-list mailing list