list IndexError

Ishwor ishwor.gurung at gmail.com
Wed Dec 22 20:41:59 CET 2004


i am trying to remove an item 'e' from the list l but i keep getting IndexError.
I know the size of the list l is changing in the for loop & its sort
of trivial task but i found no other way than to suppress the
IndexError by doing a pass. any other ways you guys can suggest? Also
is this a good or bad habit in Python? someone may perhaps suggest a
better way which i am unaware of?? the deletion could be invoked from
user input (command line) as well so its not limited to 'e'( as in my
code)

>>> l
['a', 'b', 'c', 'e', 'm']
>>> for i in range(0,len(l)):
	if l[i] == 'e': 
		l.pop(i);

		
'e'

Traceback (most recent call last):
  File "<pyshell#389>", line 2, in -toplevel-
    if l[i] == 'e':
IndexError: list index out of range
>>> l
['a', 'b', 'c', 'm']


==Using suppressing technique( a bad one though :-) )==
>>> l
['a', 'b', 'c', 'm', 'd']
>> for i in range(0,len(l)):
	try:
		if l[i] == 'e':
			l.pop(i);
	except IndexError:
		pass;
	
>>> l
['a', 'b', 'c', 'm', 'd']

==Using suppressing technique====

Any type of code changing/improving ways is heartily welcomed ;-)

-- 
cheers,
Ishwor Gurung



More information about the Python-list mailing list