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>If your values are unique, just use the <code>list.index</code> method. For example, you can do this:</p>

<pre><code>import random
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
start_l = l[:]
random.shuffle(l)
for elem in l:
    print(elem, '-&gt;', start_l.index(elem))
</code></pre>

<p>Of course, in your example this is trivial - each element is already it's initial index.</p>

<pre><code># gives the same result as above.
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(l)
for elem in l:
    print(elem, '-&gt;', elem)
</code></pre>

<p>In fact, the best method depends strongly on what you want to do. If you have other data, it might be simplest to just shuffle indices, not data. This avoids any problems of duplication etc. Basically you get a permutation list, where each element is the index the position is shifted to. For example, <code>[2, 1, 0]</code> is the permutation for reversing a list.</p>

<pre><code>l = list(random.randint(0, 10) for _ in range(10))
l_idx = list(range(len(l)))  # list of indices in l
random.shuffle(l_idx)
for new_idx, old_idx in enumerate(l_idx):
    print(l[old_idx], '@', old_idx, '-&gt;', new_idx)
</code></pre>

python