0

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 ?

Omar
  • 297
  • 5
  • 16
  • Possible duplication. Answers from the below post can clearly help you. https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list – Toothless May 04 '21 at 08:15
  • I understood your question in a way different from what other people did. You might want to [edit] your question to clarify it. Consider [mcve]. – anatolyg May 04 '21 at 08:19

4 Answers4

2

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)
sur0k
  • 334
  • 1
  • 6
0

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.

anatolyg
  • 26,506
  • 9
  • 60
  • 134
0

You can do this by just shuffling the list and picking the first item until list length > 0.

Fabio Caccamo
  • 1,871
  • 19
  • 21
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()])
avasuilia
  • 136
  • 4