list IndexError

Mike C. Fletcher mcfletch at rogers.com
Wed Dec 22 14:59:32 EST 2004


Ishwor wrote:

>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)
>  
>
Probably the most pythonic approach to this problem when dealing with 
small lists is this:

    result = [ item for item in source if item != 'e' ]

or, if you're using an older version of Python without list comprehensions:

    filter( lambda item: item!='e', source )

or even (expanding the list comprehension):

    result = []
    for item in source:
       if item != 'e':
          result.append( item )

The "python"-ness of the solutions is that we are using filtering to 
create a new list, which is often a cleaner approach than modifying a 
list in-place.  If you want to modify the original list you can simply 
do source[:] = result[:] with any of those patterns.

If you really do need/want in-place modification, these patterns are 
quite serviceable in many instances:

    # keep in mind, scans list multiple times, can be slow
    while 'e' in source:
       source.remove('e')

or (and this is evil C-like code):

    for index in xrange( len(source)-1, -1, -1 ):
       if source[i] == 'e':
          del source[i]

Keep in mind that, in the presence of threading, any index-based scheme 
is likely to blow up in your face (even the filtering solutions can 
produce unexpected results, but they are generally not going to raise 
IndexErrors due to off-the-end-of-the-list operations).

Good luck,
Mike

________________________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com




More information about the Python-list mailing list