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):


"extend.add(items)"
10 loops, best of 3: 469 msec per loop

"extend.iadd(items)"
100 loops, best of 3: 6.88 msec per loop

"extend.extend(items)"
100 loops, best of 3: 8.77 msec per loop

"extend.extend_ext(items)"
100 loops, best of 3: 6.56 msec per loop

"extend.append(items)"
100 loops, best of 3: 3.68 msec per loop

"extend.extend_no_loop(items)"
10000 loops, best of 3: 82.3 usec per loop


The definition of 'extend_no_loop' is:

def extend_no_loop(items):
  lst = []
  lst.extend(items)

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)

Cheers,
Nick.

--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---------------------------------------------------------------
            http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to