Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>import timeit def append2x(foo): foo.append(1) foo.append(1) def extend_lst(foo): foo.extend([1,1]) def extend_tup(foo): foo.extend((1,1)) l1 = [] l2 = [] l3 = [] print timeit.timeit('append2x(l1)',setup = 'from __main__ import append2x,l1') print timeit.timeit('extend_lst(l2)',setup = 'from __main__ import extend_lst,l2') print timeit.timeit('extend_tup(l3)',setup = 'from __main__ import extend_tup,l3') </code></pre> <p>Here's a simple benchmark. My results (os-X, 10.5.8, core2duo, FWIW):</p> <pre><code>0.520906925201 #append 0.602569103241 #extend-list 0.357008934021 #extend-tuple </code></pre> <p>And the same ordering of the results my linux box (Ubuntu, x86-64 core i7):</p> <pre><code>0.307395935059 #append 0.319436073303 #extend-list 0.238317012787 #extend-tuple </code></pre> <p>To me, this says that <code>extend</code> is quicker than <code>append</code>, but that creating a <code>list</code> is relatively expensive compared to creating a <code>tuple</code></p> <hr> <h1><strong>EDIT</strong></h1> <p>Pointed out in the comments below, because of the immutability of tuples, the interpreter can optimize the creation of the tuple out (it creates the tuple once and re-uses it over and over). If we change the code to:</p> <pre><code>def extend_lst(foo): v = 1 foo.extend([v,v]) def extend_tup(foo): v = 1 foo.extend((v,v)) </code></pre> <p>The timings are virtually identical:</p> <pre><code>0.297003984451 #append 0.344678163528 #extend-list 0.292304992676 #extend-tuple </code></pre> <p>Although <code>tuple</code> still consistently beats the list version and barely edges out the <code>append</code> version for all of the trials I have done.</p> <p>One thing that I'm taking away from this is that if you're iterating over an object that consists of all literals, choose a <code>tuple</code> over a <code>list</code>. If it doesn't consist entirely of literals, then it really doesn't matter whether you choose <code>list</code> or <code>tuple</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload