Reputation: 15868
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.
Upvotes: 1
Views: 1526
Reputation: 20346
As others have said, you can shuffle the list and then use the list.pop()
method. Here is an example:
>>> import random
>>> mylist = list(range(5))
>>> print(mylist)
[0, 1, 2, 3, 4]
>>> random.shuffle(mylist)
>>> print(mylist)
[4, 2, 0, 1, 3]
>>> while len(mylist) > 0:
... print(mylist.pop())
...
3
1
0
2
4
>>> print(mylist)
[]
Upvotes: 1
Reputation: 59166
Shuffle the list and pop elements from the top. That will only produce each list element once.
Upvotes: 0