newbie questions

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Sat Dec 11 07:02:26 EST 2004


houbahop wrote:
> def RAZVarAnimesDuJour(self,oSortiesAnimeTitreLabel):
>            for i in xrange(len(oSortiesAnimeTitreLabel)):
>                del oSortiesAnimeTitreLabel[i]
> 
> it doesn't emty my var (i don't want to destroy the var, just make it like 
> if it just have been created

Other posts are missing the point somewhat, I think. While they do 
recommend better ways of doing what you want to do, they don't say why 
your function doesn't work.

What exactly happens when you execute your code? When I try it, I get an 
exception:

 >>> alist = range(5)
 >>> def a(alist):
	for i in xrange(len(alist)):
		del alist[i]

		
 >>> a(alist)

Traceback (most recent call last):
   File "<pyshell#22>", line 1, in -toplevel-
     a(alist)
   File "<pyshell#21>", line 3, in a
     del alist[i]
IndexError: list assignment index out of range


What happens is this: the first time, the first element is deleted. This 
causes all other elements to shift: the second element becomes the first 
one, the third becomes the second, and so on. Or:

0, 1, 2, 3, 4
becomes
1, 2, 3, 4

The list gets shorter each time. But you're still looping over the whole 
length of the list, which means after some time you're accessing 
elements that no longer exist.

One way to solve it is to loop backwards: first delete the last element, 
than the next to last, etc.


Apart from that, it's much easier and clearer to reset the list with just

alist = []

-- 
"Codito ergo sum"
Roel Schroeven



More information about the Python-list mailing list