deleting elements from a list in a for loop

flupke flupke at nonexistingdomain.com
Fri Oct 29 10:18:25 EDT 2004


Hi,

i'm having trouble with deleting elements from a list in a for loop

============== test program ==============
el = [ "one", "two", "three", "four" ]
print "**** Start ****"
print "List = %s " % el
index = 0
for line in el:
     print "    el = %s " % line
     if ( index == 1 ):
         print "    deleting %s " % line
         del el[index]
     else:
         index += 1
print "**** After delete ****"
print "List = %s " % el

print "**** After adding two ****"
el.append("two")
print "List = %s " % el
============== test program ==============

This is the output that i get
**** Start ****
List = ['one', 'two', 'three', 'four']
     el = one
     el = two
     deleting two
     el = four
     deleting four
**** After delete ****
List = ['one', 'four']
**** After adding two ****
List = ['one', 'four', 'two']

After deleting it doesn't go to element "three". Why is that?
How can i safely delete from a list?
The reason is that i'm currently making an application to manage my 
links. I write a couple of links to the screen in a listbox (wxPython) 
and thus i delete those links that appear on screen from the list 
because people will be able to edit them.
Then when they move to another link section, i write the content of the 
listbox back to the list. But as i've illustrated in the small example 
my coding is flawed.

Thanks,
Benedict



More information about the Python-list mailing list