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>Given that you check that each value is within the list except that you must have an end of list condition, then you would have</p>

<pre><code>index = 0
while True:
    newindex = mylist[index]
    if newindex &gt;= len(mylist):
        break
    elif newindex == index:
         break
     else:
         index = newindex
</code></pre>

<p>Note that if every entry in the list is a valid index, then you would get an infinite loop.</p>

python loops for-loop iteration next