Re: Question about idioms for clearing a list



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




.



Relevant Pages

  • Lotuses from the mud of usenet - 2007 part 4 of 4
    ... What is life? ... Instead, simply watch the workings of your own mind and heart and in that movement of unforced, choiceless attention, go where you have never been before. ... -- Lee Frank ... "Then, Bahiya, you should train yourself thus: In reference to the seen, there will be only the seen. ...
    (talk.religion.buddhism)
  • Re: Inheritance of constructors.
    ... Bare in mind that was just for sake of example. ... In case of "reference by value" that's not ... Foo foo = new Foo; ... The changes to the array are visible in Foo, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: 8.1 Quake-What is this Map?
    ... mind -programmed into a reference system, ... See, Damon? ...
    (sci.geo.geology)
  • Re: quite an achievement
    ... the idea of a bounded/unbounded spectrum elsewhere in psychology. ... mind as there was already a meaningful concept implicit in the usual ... require a reference, so it is entirely spurious for RH to request ...
    (uk.sport.cricket)
  • Re: Church of Darwin
    ... Keep that in mind when you venture into your next ... obsession... ... that was his reference? ...
    (talk.origins)