Re: Question about idioms for clearing a list
- From: Tim Chase <python.list@xxxxxxxxxxxxxxxxx>
- Date: Tue, 31 Jan 2006 11:18:49 -0600
I know that the standard idioms for clearing a list are:
(1) mylist[:] = [] (2) del mylist[:]
I guess I'm not in the "slicing frame of mind", as someone put it, but can someone explain what the difference is between these and:
(3) mylist = []
Why are (1) and (2) preferred? I think the first two are changing the list in-place, but why is that better? Isn't the end result the same?
A little example will demonstrate:
>>> x = [1,2,3,4,5] >>> y = x >>> z = x >>> x = [] >>> y [1, 2, 3, 4, 5] * >>> z [1, 2, 3, 4, 5] >>> y[:]=[] * >>> z []
[*] note the differences in the results of "z", even though we've never touched "z" explicitly
By using
x = []
you set x, but you do not clear the list that other items (y & z) reference. If you use either of the two idioms you describe, you effect all items that reference that list.
-tim
.
- Prev by Date: Re: Python vs C for a mail server
- Next by Date: Re: path to python in WinXP
- Previous by thread: Re: Question about idioms for clearing a list
- Next by thread: psycopg2
- Index(es):
Relevant Pages
|