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

BartC bc at freeuk.com
Thu Mar 24 11:18:49 EDT 2016


On 24/03/2016 15:03, Jon Ribbens wrote:
> On 2016-03-24, BartC <bc at freeuk.com> wrote:
>> On 24/03/2016 14:08, Jon Ribbens wrote:
>>> 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.
>
> No it isn't, it's replacing the elements in-place,

Replace them with what, if not an entirely new list built from 
'[0]*len(L)'? (And which would briefly require twice the memory occupied 
by the old list, if I'm not mistaken.)

>> 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?
>
> I think it would depend on how many elements you were changing and
> why. It doesn't come up all that often because of the ease in which
> Python functions can return multiple values but sometimes you might
> make a function which takes as a parameter a list which the function
> will mutate.

Answering my own question, obviously changing some elements of a list 
has to be Pythonic, otherwise there wouldn't be lists, only non-mutable 
tuples. Although I was talking more within the context of a for-in loop.

-- 
Bartc





More information about the Python-list mailing list