Skip to content Skip to sidebar Skip to footer

Getting Previous Index Values Of A Python List Items After Shuffling

Let's say I have such a python list: l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] by using random.shuffle, >>> import random >>> random.shuffle(l) >>> l [5, 3, 2

Solution 1:

You could pair each item with its index using enumerate, then shuffle that.

>>> import random
>>> l = [4, 8, 15, 16, 23, 42]
>>> x = list(enumerate(l))
>>> random.shuffle(x)
>>> indices, l = zip(*x)
>>> l
(4, 8, 15, 23, 42, 16)
>>> indices
(0, 1, 2, 4, 5, 3)

One advantage of this approach is that it works regardless of whether l contains duplicates.


Solution 2:

If your values are unique, just use the list.index method. For example, you can do this:

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, '->', start_l.index(elem))

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

# 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, '->', elem)

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, [2, 1, 0] is the permutation for reversing a list.

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, '->', new_idx)

Solution 3:

To keep track of everything using a dictionary, one can do this:

Use enumerate in your dictionary comprehension to have index and value in your iteration, and then assign value as key, and index as value.

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)

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

However, if your list will contain duplicates, this answer from Kevin should be referred to.


Solution 4:

A more intuitive alternative to the other answers:

Shuffle a range of indices, and use that to get a shuffled list of the original values.


Solution 5:

Create a copy of the original list and shuffle the copy:

>>> import random    
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l_copy = list(l)  # <-- Creating copy of the list
>>> random.shuffle(l_copy)  # <-- Shuffling the copy
>>> l_copy   # <-- Shuffled copy               
[8, 7, 1, 3, 6, 5, 9, 2, 0, 4]
>>> l   # <-- original list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

Post a Comment for "Getting Previous Index Values Of A Python List Items After Shuffling"