On 24 March 2016 at 14:04, BartC <b...@freeuk.com> wrote: >On 24/03/2016 13:50, Steven D'Aprano wrote: >> for i in range(len(mylist)-1, -1, 0): >> del mylist[i] > > That's wouldn't be I'd call clearing a list, more like destroying it > completely!
Look more closely. The semantics of using the del keyword with an index are to delete that element. The list isn't destroyed, it just has each element removed in turn. The point is that one can just do `mylist.clear()` > How would you actually clear a list by traversing it (ie. not just building > a new one)? > > This doesn't work: > > for x in L: > x=0 > > as each x only refers to the value in each element of L, not the element > itself (like the pass-by-reference problem). > > I'd presumably have to do: > > for i in range(len(L)): > L[i]=0 That doesn't clear the list, that results in a list of the same length where every element is 0. That might sound like the same thing if you're used to a bounded array of ints, for example, but in Python it's very much not. -- Matt Wheeler http://funkyh.at -- https://mail.python.org/mailman/listinfo/python-list