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>Here's one way to do it with <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count</code></a>. </p>

<p><code>groupby</code> on the key function <code>lambda _: next(c)//3</code> groups the items in the iterables in <em>threes</em>  in successions. The logic uses the integer division of the next object in the count item on 3:</p>

<pre><code>from itertools import groupby, count

L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'

c = count()    
for _, g in groupby(L, lambda _: next(c)//3):
    item = head + ''.join(map(str, g)) + tail
    print(item)
</code></pre>

<p><em>Output</em>:</p>

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

python