Getting previous index values of a python list items after shuffling
<p>Let's say I have such a python list:</p>

<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>

<p>by using <code>random.shuffle</code>, </p>

<pre><code>&gt;&gt;&gt; import random
&gt;&gt;&gt; random.shuffle(l)
&gt;&gt;&gt; l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
</code></pre>

<p>I am having the above list.</p>

<p>How can I get the previous index values list of each item in the shuffled list? </p>

<p>To keep track of everything using a dictionary, one can do this: </p>

<p>Use <code>enumerate</code> in your dictionary comprehension to have index and value in your iteration, and then assign value as key, and index as value. </p>

<pre><code>import random

l = [5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
d = {v: i for i, v in enumerate(l)}
print(d) # current state
random.shuffle(l)
</code></pre>

<p>The advantage here is that you get <code>O(1)</code> lookup for retrieving your index for whatever value you are looking up. </p>

<p>However, if your list will contain duplicates, <a href="http://stackoverflow.com/a/39832854/1832539">this</a> answer from Kevin should be referred to.</p>

python