How to iterate in a certain order?
<p>I'm wondering how I can iterate through a list in a certain order in Python.</p>

<p>Given the list, <code>lst = [1, 3, -1, 2]</code>, I want my function to iterate such that the next number iterated over will be the index of the value of the current number.</p>

<p>lst[0] -> lst[1] -> lst[3] -> lst[2]
1 -> 3 -> 2 -> -1</p>

<p>There are a couple variables that you have not specified:</p>

<ol>
<li>What kind of error handling should this include? </li>
<li>Do you want it to loop indefinitely?</li>
</ol>

<p>Assuming that the respective answers are "None" and "Yes", here's one way of doing it:</p>

<pre><code>def create_iter(arr):
    i = 0
    while True:
        yield arr[i]
        i = arr[i]

lst = [1,3,-1,2]
my_iterator = create_iter(lst)
</code></pre>

<p>This gives:</p>

<pre><code>&gt;&gt;&gt; for _ in range(10):
&gt;&gt;&gt;    print (next(my_iterator))
1
3
2
-1
2
-1
2
-1
2
-1
</code></pre>

python loops for-loop iteration next