title: how to split an iterable in constant-size chunks
body: <p>I am surprised I could not find a &quot;batch&quot; function that would take as input an iterable and return an iterable of iterables.</p>
  <p>For example:</p>
  <pre><code>for i in batch(range(0,10), 1): print i
  [0]
  [1]
  ...
  [9]
  </code></pre>
  <p>or:</p>
  <pre><code>for i in batch(range(0,10), 3): print i
  [0,1,2]
  [3,4,5]
  [6,7,8]
  [9]
  </code></pre>
  <p>Now, I wrote what I thought was a pretty simple generator:</p>
  <pre><code>def batch(iterable, n = 1):
     current_batch = []
     for item in iterable:
         current_batch.append(item)
         if len(current_batch) == n:
             yield current_batch
             current_batch = []
     if current_batch:
         yield current_batch
  </code></pre>
  <p>But the above does not give me what I would have expected:</p>
  <pre><code>for x in   batch(range(0,10),3): print x
  [0]
  [0, 1]
  [0, 1, 2]
  [3]
  [3, 4]
  [3, 4, 5]
  [6]
  [6, 7]
  [6, 7, 8]
  [9]
  </code></pre>
  <p>So, I have missed something and this probably shows my complete lack of understanding of python generators. Anyone would care to point me in the right direction ?</p>
  <p>[Edit: I eventually realized that the above behavior happens only when I run this within ipython rather than python itself]</p>