Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This seems tailor-made for a <code>collections.deque</code> since you essentially have a FIFO (add to one end, remove from the other). However, even if you use a <code>list</code> you shouldn't be slicing twice; instead, you should probably just <code>pop(0)</code> from the list and <code>append()</code> the new item.</p> <p>Here is an optimized deque-based implementation patterned after your original:</p> <pre><code>from collections import deque def window(seq, n=2): it = iter(seq) win = deque((next(it, None) for _ in xrange(n)), maxlen=n) yield win append = win.append for e in it: append(e) yield win </code></pre> <p>In my tests it handily beats everything else posted here most of the time, though pillmuncher's <code>tee</code> version beats it for large iterables and small windows. On larger windows, the <code>deque</code> pulls ahead again in raw speed.</p> <p>Access to individual items in the <code>deque</code> may be faster or slower than with lists or tuples. (Items near the beginning are faster, or items near the end if you use a negative index.) I put a <code>sum(w)</code> in the body of my loop; this plays to the deque's strength (iterating from one item to the next is fast, so this loop ran a a full 20% faster than the next fastest method, pillmuncher's). When I changed it to individually look up and add items in a window of ten, the tables turned and the <code>tee</code> method was 20% faster. I was able to recover some speed by using negative indexes for the last five terms in the addition, but <code>tee</code> was still a little faster. Overall I would estimate that either one is plenty fast for most uses and if you need a little more performance, profile and pick the one that works best.</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. 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