how to print this pattern using python iterator
<pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'
</code></pre>

<p>suppose we can and can only get the iterator of some iterable(L).
and we can not know the length of L.
Is that possible to print the iterable as:</p>

<pre><code>'head123tail'
'head456tail' 
'head789tail' 
'head10tail'
</code></pre>

<p>My try at it is as follows.</p>

<pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'
slice_size = 3

i = iter(L)
try:
    while True:
        counter = 0
        while counter &lt; slice_size:
            e = next(i)
            if counter == 0:
                print(head, end='')
            print(e, end='')
            counter += 1
        else:
            print(tail)
except StopIteration:
    if counter &gt; 0:
        print(tail)
</code></pre>

<p>You can <a href="http://stackoverflow.com/a/24527424/1639625">split the iterator into chunks</a> of three, using <code>chain</code> and <code>slice</code> from <code>itertools</code> and a <code>for</code> loop, and then join them. The <code>for</code> loop will do most of what your <code>try/while True/except</code> construct is doing.</p>

<pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'
slice_size = 3
iterator = iter(L)

from itertools import chain, islice
for first in iterator:
    chunk = chain([first], islice(iterator, slice_size - 1))
    print(head, ''.join(str(x) for x in chunk), tail)
</code></pre>

<p>However, if your iterator is just a <code>list</code>, you can just use <code>range</code> with a <code>step</code> parameter:</p>

<pre><code>for start in range(0, len(L), slice_size):
    chunk = L[start : start + slice_size]
    print(head, ''.join(str(x) for x in chunk), tail)
</code></pre>

python