I would like to random shuffle a list so that each variable in the list when shuffled gets put in a new place in the list.
What I am currently doing:
list = ['a', 'b','c', 'd'];
random.shuffle(list)
list
['c','b','d','a']
With this method I shuffle the list but it is still possible to have a variable end up in the same place in this case 'b'.
My desired output
completely shuffled list
['c','a','d','b']
I appreciate any help. I am new to python but please let me know if any further information is needed.
Something like this should do what you want:
import random
import copy
def super_shuffle(lst):
new_lst = copy.copy(lst)
random.shuffle(new_lst)
for old, new in zip(lst, new_lst):
if old == new:
return super_shuffle(lst)
return new_lst
Example:
In [16]: super_shuffle(['a', 'b', 'c'])
Out[16]: ['b', 'c', 'a']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With