On 2016-03-24, BartC <b...@freeuk.com> wrote: > On 24/03/2016 13:50, Steven D'Aprano wrote: >> Likewise clearing a list: >> >> 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! > > 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's kind've a weird thing to want to do; if you thought you needed to do that then most likely what you should actually be doing is re-writing your code so you no longer need to. However, you could do: L[:] = [0] * len(L) -- https://mail.python.org/mailman/listinfo/python-list