Function to shuffle a list completely

I need a function to shuffle a list e.g. a = [1, 2, 3, 4] so that the order becomes completely different (the number at each position is different from the original one). I find the following code (with some modifications), but the zip() function cannot be translated to JS automatically.

``````import random

def shuffle_list(some_list):
randomized_list = some_list[:]
while True:
random.shuffle(randomized_list)
for a, b in zip(some_list, randomized_list):
if a == b:
break
else:
return randomized_list
``````

I tried to modify it as the follow but it can only partly shuffle the order:

``````def myFun_shuffle_sequence_order(study_order_list, sl):
test_order_list = study_order_list[:]
while True:
shuffle(test_order_list)
for i in range(sl):
for j in range(sl):
if i == j and test_order_list[i] == study_order_list[j]:
break
else:
return test_order_list

shuffle_sequence_order = myFun_shuffle_sequence_order
``````

I’d appreciate if there is any suggestion on how to accomplish this both offline and online! Thanks as always.

Are you avoiding shuffle(myList) because some elements may end up in the unchanged?

Yes, I want it to be completely shuffled so that the number at each position is different from the old one.

Shouldn’t this be

``````for i in range(sl):
if test_order_list[i] == study_order_list[i]:
break
``````

Oh yes! Seems it’s working. Sorry I overthought. Thanks!

Hi Wake, sorry to bother you again-do you have any idea how to translate this code to JS? With the automatic translation the online exp got stuck with no error. I tried to modify it but cannot make it run. Or is there an easier way to accomplish my goal? Thanks!

This is my Python code, offline, it suffles a list completely with no problem.

``````def myFun_shuffle_sequence_order(study_order_list, sl):
test_order_list = study_order_list[:]
while True:
shuffle(test_order_list)
for i in range(sl):
if test_order_list[i] == study_order_list[i]:
break
else:
return test_order_list

shuffle_sequence_order = myFun_shuffle_sequence_order
``````

The automatic translated JS code (I search online JS does not have the for/else loop as in Python, that’s might be the problem):

``````function myFun_shuffle_sequence_order(study_order_list, sl) {
var test_order_list;
test_order_list = study_order_list.slice(0);
while (true) {
shuffle(test_order_list);
for (var i, _pj_c = 0, _pj_a = range(sl), _pj_b = _pj_a.length; (_pj_c < _pj_b); _pj_c += 1) {
i = _pj_a[_pj_c];
if ((test_order_list[i] === study_order_list[i])) {
break;
}
}
}
}
shuffle_sequence_order = myFun_shuffle_sequence_order;
``````