list addition methods compared.
Terry Reedy
tjreedy at udel.edu
Sun Dec 26 18:37:35 EST 2004
"Ishwor" <ishwor.gurung at gmail.com> wrote in message
news:34534aed04122615176056a0a9 at mail.gmail.com...
> On Sun, 26 Dec 2004 04:57:17 -0500, Terry Reedy <tjreedy at udel.edu> wrote:
>>
>> "Ishwor" <ishwor.gurung at gmail.com> wrote in message
>> news:34534aed0412252012638c85fd at mail.gmail.com...
>> > Hi all
>> > I have just wrote a small script to compare the speed of list addition
>> > methods.
>>
>> There are two meanings of 'list addition':
>>
>> li = li+[item] *copies* the list and adds item
>>
>> li += [item] is the same as li.extend([item]) which add item to the end
>> of
>> the list *without* copying.
>>
>> Of course, extending a list is faster than copying + one more.
>>
>
> I agree with you that list extending is faster way to add as compared
> to method 1. also that method 2 is mapped to 'extend()' anyway,
As near as I could tell from what you posted (and I snipped), method 2 was
about the same as 1 and not mapped to extend().
> but
> why is the method 3 ( l3.extend() ) in my example code talking only
> nearly 1% of time to complete as compared to method 1/2???
Because writing 1 pointer takes 1/100th as long as writing 100 pointers (in
the C code of CPython). You used lists long enough for the difference
between O(n) and O(n**2) behavior to show.
> Thanks Terry for yet another small (really small) step towards
> enlightment.
You're welcome. Hope this is another small step ;-)
Terry J. Reedy
More information about the Python-list
mailing list