0

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?

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.