Reputation: 321
I have the following array
a = [1, 2, 5, 4, 3, 6, 1]
And I want to know how I can shuffle any two values randomly within an array that isn't either the first or last value. Some examples of the desired results below:
Output =
[1, 4, 5, 2, 3, 6, 1]
[1, 2, 3, 4, 5, 6, 1]
[1, 6, 5, 4, 3, 2, 1]
[1, 3, 5, 4, 2, 6, 1]
Is there a way to do this in python?
Upvotes: 0
Views: 45
Reputation: 3046
Try this,
import random
from random import shuffle
a = [1, 2, 5, 4, 3, 6, 1]
hold = a[1:-1]
random.shuffle(hold)
shuffled_list = [a[0]] + hold + [a[-1]]
shuffled_list
>>
Out[87]:
[1, 5, 4, 3, 6, 2, 1]
Upvotes: 2