Re: Removing elements from a list while ite

Robin Friedrich (friedric@rose.rsoc.rockwell.com)
12 Mar 1995 20:19:12 GMT

|Another way of doing this is to iterate backwards over your big list
|and without making a copy:
|
|list = [ <YourVeryHugeList> ]
|i = len(list)
|
|while i != 0:
| i = i - 1
| if list[i] matches some criterion:
| do something with list[i]
|
|It works fine for the small tests I tried (on a list of numbers, with modulo
|as a test and 'del' as the doSomething part). Is it safe, anyone?
|
|Magnus Lindberg
|#include <disclaimer.h>

Yes this is safe. I've used this quite often to save myself the trouble
of copying lists all over the place. When I don't have a huge list to
deal with I also use:

for i in range(len(list)-1, 0, -1):
if list[i] != pretty:
del list[i]

--------------------------------------------------------------
| Robin K. Friedrich | friedric@rsoc.rockwell.com |
| Rockwell Space Operations | (713) 282-2974 |
| Houston, TX | |
--------------------------------------------------------------