[Tutor] modifying array during 'for' loop?

Ivan Van Laningham ivanlan@callware.com
Thu, 03 Feb 2000 16:45:10 -0700


Hi All--

Neil Conway wrote:
> 
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> I was just wondering if it is always okay to modify the array you are
> looping through with a for loop (i.e. modify the array -during- the
> for loop). Is it okay to delete the current item from the list? what
> about items other than the current item? What about append items to
> the end of the array, or slice the array?
> 
> I'm dealing with lists (scalar arrays) and tuples. If I'm not being
> clear, I would be happy to provide example code.
> 
> While I'm on the topic, I have always assumed that a tuple is
> marginally more efficient than a list. Is this true?
> 

It's never OK.  Something like it can be done, but it really is a form
of do-it-yourself brain surgery.

Never do

	for i in alist:
		alist.remove(i)

If you *insist* on modifying a list when you're looping on it, then the
closest you're going to get to safety (which ain't close) is to peel
things off the end of the list and make sure you never access them
again.  That is, look up the doc for range and get a range that counts
backwards.  Use the current index to remove or modify the item, as in

	for i in range(len(alist),-1,-1):
		del alist[i]

Tuples are more efficient in that they're read-only and don't have
methods.  But the only way to modify them, once created, is to nuke 'em
and recreate them.  If you're going to modify them, lists are more
efficient.

<hand-me-my-power-drill>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan@callware.com
ivanlan@home.com
http://www.pauahtun.org
See also: 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
----------------------------------------------