How to shuffle nested list while keeping the last element stationary

Question:

I have a nested list. I am thinking of a way to randomize the list without shifting the last element ‘(‘hi’, ‘string)’

nested = [[('1','integer'), ('2', 'integer')],[('3', 'integer'), ('4', 'integer')], [('hi', 'string')]

I have tried using this method:

import random
A = [[('1','integer')], [('2', 'integer')], [('3', 'integer')], [('hi', 'string')]]


random.Random(9).shuffle(A)
print(A)

Result

[[('1', 'integer')], [('2', 'integer')], [('3', 'integer')], [('hi', 'string')]]

^^This method is not good if you want to shift the last element because if u set the position to the end you will realise that the order of the list have not been changed.

However, if the nested list were to increase in length, the number in Random will not be 9 anymore. Is there a way to just make the last element stay as (‘hi’, ‘string’) while the rest of the elements shift positions

Asked By: Johny Lau

||

Answers:

import random

*shuffled, last = nested # remove last element from list
random.shuffle(shuffled) # shuffle list
shuffled.append(last)    # add back last element
Answered By: Gábor Fekete
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.