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)
[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'e', 'm'][color=blue][color=green][color=darkred]
>>> for i in range(0,len(l)) :[/color][/color][/color]
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[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'm']
==Using suppressing technique( a bad one though :-) )==[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'm', 'd'][color=blue][color=green]
>> for i in range(0,len(l)) :[/color][/color]
try:
if l[i] == 'e':
l.pop(i);
except IndexError:
pass;
[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'm', 'd']
==Using suppressing technique====
Any type of code changing/improving ways is heartily welcomed ;-)
--
cheers,
Ishwor Gurung
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)
[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'e', 'm'][color=blue][color=green][color=darkred]
>>> for i in range(0,len(l)) :[/color][/color][/color]
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[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'm']
==Using suppressing technique( a bad one though :-) )==[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'm', 'd'][color=blue][color=green]
>> for i in range(0,len(l)) :[/color][/color]
try:
if l[i] == 'e':
l.pop(i);
except IndexError:
pass;
[color=blue][color=green][color=darkred]
>>> l[/color][/color][/color]
['a', 'b', 'c', 'm', 'd']
==Using suppressing technique====
Any type of code changing/improving ways is heartily welcomed ;-)
--
cheers,
Ishwor Gurung
Comment