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

BartC bc at freeuk.com
Thu Mar 24 10:16:06 EDT 2016


On 24/03/2016 14:08, Jon Ribbens wrote:
> 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;

The thing I'm trying to demonstrate is changing an element of a list 
that you are traversing in a loop. Not necessarily set all elements to 
the same value.

  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)

OK, but that's just building a new list as I've already mentioned.

Or is the Pythonic way, when you want to change some elements of a list 
to just build a new one that incorporates those changes?

-- 
Bartc



More information about the Python-list mailing list