Is this a safe thing to do?

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Oct 9 08:51:55 EDT 2003


phil_nospam_schmidt at yahoo.com (Phil Schmidt) wrote in 
news:221e7b06.0310090440.727cf10f at posting.google.com:

> The following example works fine (Python 2.3), but is it always safe
> to modify a list that is being iterated in a loop, regardless of the
> actual contents of the list x? If not, what's a better (safe) way to
> do it?

No, it is never safe to do this, you might skip over list elements. For 
example, a very small change to your data shows it going wrong:

>>> x=[{'f':9},{'f':1},{1:3,'f':9},{'f':9},{'f':3}]
>>> for t in x:
	if t['f'] == 9:
		x.remove(t)

		
>>> x
[{'f': 1}, {'f': 9}, {'f': 3}]
>>> 

The answer is to iterate over a COPY of the list if you want to modify it 
during the iteration:

>>> x=[{'f':9},{'f':1},{1:3,'f':9},{'f':9},{'f':3}]
>>> for t in list(x):
	if t['f'] == 9:
		x.remove(t)

		
>>> x
[{'f': 1}, {'f': 3}]
>>> 

Copying the list may be done by using the 'list' builtin, by using an empty 
slice, or using 'copy.copy'.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list