list addition methods compared.

Nick Coghlan ncoghlan at
Mon Dec 27 03:30:40 CET 2004

Steven Bethard wrote:
> (1) I didn't see the top of this thread, but I'm assuming that you've 
> got a conditional or something in your real loop or you could just use 
> lst.extend(items) without ever iterating over the items list.  Your real 
> code may actually require extend-style functionality, but as the results 
> above show, if you really only have one item to add, list.append is 
> definitely the better way to go.

Just to prove Steven's point about avoiding the for loop if you can (timings 
here use the same timeit command as Steven did):

10 loops, best of 3: 469 msec per loop

100 loops, best of 3: 6.88 msec per loop

100 loops, best of 3: 8.77 msec per loop

100 loops, best of 3: 6.56 msec per loop

100 loops, best of 3: 3.68 msec per loop

10000 loops, best of 3: 82.3 usec per loop

The definition of 'extend_no_loop' is:

def extend_no_loop(items):
   lst = []

Note that if you do have a conditional expression in the for loop (e.g. "only 
add items greater than zero", it is worth checking the timings for calling 
extend with a generator expression or list comprehension that filters out the 
values you don't want)


Nick Coghlan   |   ncoghlan at   |   Brisbane, Australia

More information about the Python-list mailing list