The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Jon Ribbens jon+usenet at unequivocal.co.uk
Thu Mar 24 10:08:07 EDT 2016


On 2016-03-24, BartC <bc at 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)



More information about the Python-list mailing list