May I loop over a changing list?

Skip Montanaro skip at mojam.com
Wed Sep 22 10:47:12 EDT 1999


    > Olaf Delgado writes:
    >> I am whondering whether the following is considered good (and,
    >> more important: save) programming style in python:

    Charles> No, you must never modify a list your are iterating over.

The tutorial notwithstanding, it's sometimes desirable to not copy lists you
are iterating over (like when they code the E. Coli DNA sequence).  How you
iterate over a changing list is going to be dependent on how you want to
change it.  If you only need to append to the list, you may find looping
over the indexes of the list adequate:

    for i in range(len(mylist)):
	if mylist[i] == "a":
	   mylist.append(mylist[i])

This also works for simple replacement:

    for i in range(len(mylist)):
	if mylist[i] == "a":
	   mylist[i] = "b"

In situations where you want to delete items from the list as they are
encountered, you can iterate backwards:

    for i in range(len(mylist)-1,-1,-1):
	if mylist[i] == "z":
	   del mylist[i]

You can probably come up with other ad hoc schemes for multi-element
insertions and deletions.  I'll leave those to your imagination.

where-there's-a-will-there's-a-way-ly y'rs,

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/~skip/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list