Is there a way to "pseudo"-randomly select an element from a list that wasn't chosen before? I know about the
choice function, which returns a random item from the list, but without taking into account previous chosen items. I could keep track of which elements were already picked, and keep randomly choose another not yet selected item, but this might include nested loops, etc.
I could also for example remove the element chose from the list at each iteration, but this does not seem a good solution, too.
My question is: is there a "aware"
choice function that selects only items that weren't chosen before? Note that I'm not asking how to implement such a function, but possible solutions are of course well-accepted too.
As others have said, you can shuffle the list and then use the
list.pop() method. Here is an example:
>>> import random >>> mylist = range(5) >>> print(mylist) [0, 1, 2, 3, 4] >>> random.shuffle(mylist) >>> print(mylist) [4, 2, 5, 1, 3] >>> while len(mylist) > 0: ... print(mylist.pop()) ... 3 1 5 2 4 >>> print(mylist)