I want to iterate through list with random values. However, I want the item that has been picked to be removed from the list for the next trial, so that I can avoid picking the same item in a row; but it should be added back again after.
please help me on showing that on this simple example. Thank you
import random
l = [1,2,3,4,5,6,7,8]
for i in l:
print random.choice(l)
Both work for list of non-unique elements as well:
def choice_without_repetition(lst):
prev = None
while True:
i = random.randrange(len(lst))
if i != prev:
yield lst[i]
prev = i
or
def choice_without_repetition(lst):
i = 0
while True:
i = (i + random.randrange(1, len(lst))) % len(lst)
yield lst[i]
Usage:
lst = [1,2,3,4,5,6,7,8]
for x in choice_without_repetition(lst):
print x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With