list addition methods compared.

Terry Reedy tjreedy at udel.edu
Mon Dec 27 01:07:01 EST 2004


"Ishwor" <ishwor.gurung at gmail.com> wrote in message 
news:34534aed0412261603279c1096 at mail.gmail.com...

If you are curious about the detailed behavior of the CPython 
implementation, the dis module is one aid.  Compare

>>> def f1(l):
...   l.extend([1])
...   return l
...
>>> def f2(l):
...   l += [1]
...   return l
...
>>> import dis
>>> dis.dis(f1)
          0 SET_LINENO               1

          3 SET_LINENO               2
          6 LOAD_FAST                0 (l)
          9 LOAD_ATTR                1 (exten
         12 LOAD_CONST               1 (1)
         15 BUILD_LIST               1
         18 CALL_FUNCTION            1
         21 POP_TOP

         22 SET_LINENO               3
         25 LOAD_FAST                0 (l)
         28 RETURN_VALUE
         29 LOAD_CONST               0 (None)
         32 RETURN_VALUE
>>> dis.dis(f2)
          0 SET_LINENO               1

          3 SET_LINENO               2
          6 LOAD_FAST                0 (l)
          9 LOAD_CONST               1 (1)
         12 BUILD_LIST               1
         15 INPLACE_ADD
         16 STORE_FAST               0 (l)

         19 SET_LINENO               3
         22 LOAD_FAST                0 (l)
         25 RETURN_VALUE
         26 LOAD_CONST               0 (None)
         29 RETURN_VALUE

Since INPLACE_ADD ends up calling .extend, the direct call should, on 
average, be slightly faster.  But the difference is comparable to the noise 
of the variation in memory allocation time.

l.append(item) might be even faster than l.extend([item]), especially when 
item is not a contant, since the unneeded list is not built.

Terry J. Reedy






More information about the Python-list mailing list