iterating through lists to delete elements

Mark Robinson m.1.robinson at herts.ac.uk
Thu Aug 9 10:54:40 EDT 2001


Can anyone advise me the best way to iterate through a list and deleting 
elements that don't meet a certain criteria.

If I use:
for x in list:
	if x > y:
		del x

obviously that just deletes a reference to a list element

I also can't do:

for x in range(len(list)):
	if list[x] < y:
		del list[x]

cos if I actually delete anything I will miss some list elements and run 
off the end of the list.

I have been using the following methods:

toDel = []
for x in range(len(list)):
	if list[x] < y:
		toDel.append(x)
toDel.reverse()
for x in toDel:
	del list[x]

(blech)
or

x = 0
while x < len(list):
	if list[x] < y:
		del list[x]
	else:
		x += 1

Thats the nicest way I can think of, but I was just wondering if there 
is a prefered idiom or if anyone can suggest a nicer way. It is a 
routine I seem to use alot.

cheers
Blobby
	




More information about the Python-list mailing list