modifying mutable list elements in a for loop

David Stockwell winexpert at hotmail.com
Wed May 26 08:46:07 EDT 2004


Hi,

I'm no expert in python (only a beginner), so my words here probably should 
be taken with caution...

Anyways i would think you are fine.  You didn't modify the sequence that 
comprises 'a'.

A is a list of objects.  the list stayed the same.

Each object did indeed change, but the reference to them (stored in a) 
hasn't changed).

Therefore I would think its ok.

However, I will eagerly wait and see how the gurus answer this question as 
it will be a good learning experience.



David
-------
Cell: http://cellphone.duneram.com/index.html
Cam: http://www.duneram.com/cam/index.html
Tax: http://www.duneram.com/index.html




>From: pballard at ozemail.com.au (Peter Ballard)
>To: python-list at python.org
>Subject: modifying mutable list elements in a for loop
>Date: 26 May 2004 05:39:07 -0700
>
>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/
>--
>http://mail.python.org/mailman/listinfo/python-list

_________________________________________________________________
Learn to simplify your finances and your life in Streamline Your Life from 
MSN Money. http://special.msn.com/money/0405streamline.armx





More information about the Python-list mailing list