Modifying list/dictionary elements whilst iterating???

Moshe Zadka moshez at math.huji.ac.il
Thu Feb 17 13:45:28 EST 2000


On Thu, 17 Feb 2000, Philip Payne wrote:

> I know it's not allowed to add/remove elements from lists/dictionaries
> whilst iterating over them, but can someone give me a definitive answer as
> to whether modifying list/dictionary values as follows whilst iterating is
> safe:
> 
> d = {'the' : 1, 'cat' : 2, 'sat' : -4}
> print 'before', d
> for key,value in d.items() :
>     value = value + 1
>     d[key] = value
> print 'after', d

> l = [1,2,3,4,5]
> print 'before', l
> for i in xrange(len(l)) :
>     l[i] = l[i] + 1
> print 'after', l

Both are safe. The first because the results of the .items() is computed
long before the dictionary has any chance of changing. The second is safe
because the results of the xrange() are computed long before the list
has any chance of changing.
--
Moshe Zadka <mzadka at geocities.com>. 
INTERNET: Learn what you know.
Share what you don't.





More information about the Python-list mailing list