Index into a Python iterator
<p>I have an iterator <code>iterator</code> and a list of indices <code>indices</code> (repeats possible) and I want to extract just those elements from my iterator. At the moment I'm doing</p>

<pre><code>indices = sorted(indices)
deltas = [indices[0]] + [indices[i+1] - indices[i] for i in range(len(indices) - 1)]
output = []
for delta in deltas:
    for i in range(delta):
        datum = next(iterator)
    output.append(datum)
</code></pre>

<p>Are those two layers of loop necessary? Am I missing a trick with <code>itertools</code>?</p>

<p>If memory isn't a constraint, I would just find the max index and prepopulate an array of iterator values up to that max index.  You're going to have to compute the intermediate values anyway, so you really don't gain anything by computing the deltas.</p>

<pre><code>max_index = max(indices)
data = [v for v in itertools.islice(iterator, max_index + 1)]
values = [data[i] for i in indices]
</code></pre>

python iterator itertools