Coding style

Tim Chase python.list at tim.thechases.com
Mon Jul 17 12:26:36 EDT 2006


> lst = [1,2,3,4,5]
> while lst:
>     lst.pop()
> 
> Or even just:
> 
> lst = []

Subtly different though...

 >>> while lst:
...     lst.pop()
...
5
4
3
2
1
 >>> lst2
[]
 >>> lst = [1,2,3,4,5]
 >>> lst2 = lst
 >>> lst = []
 >>> lst2
[1, 2, 3, 4, 5]
 >>> lst = [1,2,3,4,5]
 >>> lst2 = lst
 >>> del lst[:]
 >>> lst2
[]

The original while loop changes the actual list, reassigning it 
to a new list prevents other items that reference that list from 
accessing the changes.  As shown above, I recommend

	del lst[:]

which should be as fast as python will let one do it. (maybe? 
again with those timeit guys... ;)

-tkc







More information about the Python-list mailing list