list IndexError

Mike C. Fletcher mcfletch at rogers.com
Wed Dec 22 18:12:26 EST 2004


Ishwor wrote:
...

>I believe lamda's are unnamed functions aren't they?? Still learning... ;-)
>  
>
Yes.

>yeah actually i saw what Fedrik had to say above. I created a sliced
>copy of the l & did my homework within the for loop
>  
>
You might want to check it again before you hand it in ;) ...

 >>> def ishwor( source ):
...     for item in source:
...         if item == 'd':
...             source.remove( item )
...            
 >>> d = ['a','b','c','d','e']
 >>> ishwor( d )
 >>> d
['a', 'b', 'c', 'e']

Well, that worked fine, but wait a minute...

 >>> d = ['a','b','c','d','d','e']
 >>> ishwor( d )
 >>> d
['a', 'b', 'c', 'd', 'e']

This is the same problem as you saw before.  Under the covers, the 
Python interpreter is written such that it's keeping track of the index 
into the list as an integer.  When you mutate the list, that integer 
gets out-of-sync with the value you think you're processing.

The while form I provided avoids that by re-scanning the *whole* list 
every time it does the check.  The filtering forms do it by working on a 
temporary list.  The reverse-index form does it by only deleting from 
the segment of the list *after* the point where the to-be-done indices 
reference.

>This code is so clean and looks very healthy. :) Python will live a
>long way because its a cute language. :-)
>  
>
Cute is, of course, the highest praise to which any man, woman or 
language can aspire :) .

>>   for index in xrange( len(source)-1, -1, -1 ):
>>      if source[i] == 'e':
>>         del source[i]
>>
>>    
>>
>thanx Mike, i have tried this C-ish way as well . :-) it seemed quiete
>ok for my  small list but dont know about huge lists.
>  
>
It's actually *good* for huge lists where you only want to delete a few 
items, that's it's main attraction, it doesn't copy the list at all 
(though each deletion causes a memcopy of all pointers from that element 
in the list onward, that's a fairly faster operation).  It's going to 
avoid new memory allocation much of the time, and doesn't have the "scan 
the whole list for each deletion" overhead of the "while x in list" version.

Anyway, have fun,
Mike

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




More information about the Python-list mailing list