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
Answers:
import random
*shuffled, last = nested # remove last element from list
random.shuffle(shuffled) # shuffle list
shuffled.append(last) # add back last element
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
import random
*shuffled, last = nested # remove last element from list
random.shuffle(shuffled) # shuffle list
shuffled.append(last) # add back last element