I have a list lets say x = [8,6,4,1]
I want to pick a random element from this list in Python but each time picking this item shouldn't be the same item picked previously. So I don't want a repetition
How can I do this ?
I have a list lets say x = [8,6,4,1]
I want to pick a random element from this list in Python but each time picking this item shouldn't be the same item picked previously. So I don't want a repetition
How can I do this ?
Use random
package
import random
x = [8,6,4,1]
random.shuffle(x)
for number in x:
print(number)
One note here: shuffle
doesn't return anything (well, None
actually). Instead of returning a new list, it mutates it. That means that you're unable to use it into a loop declaration
for number in random.shuffle(x): # TypeError: 'NoneType' object is not iterable
print(number)
If you are using randrange
to generate a random index, use a range smaller by 1, because there is one forbidden index. To convert the output of randrange
to the needed range (with one number removed), conditionally add 1 to the number.
def random_choice_without_repetition(list x, int forbidden_index):
index = random.randrange(len(list) - 1)
if index >= forbidden_index:
index += 1
return index
This code returns an index instead of the element itself, because it wants to receive the forbidden index. You might want to adapt it to your use case to make it more convenient.
You can do this by just shuffling the list and picking the first item until list length > 0.
import random
x = [8,6,4,1]
y = range(len(x))
random.shuffle(y)
Now each time you want to pick a random element do:
print(x[y.pop()])