-1

I am wondering if their is any way to make a random.choice command not chose the same twice

for example:

import random
temp = 0
list_ = ["apple", "orange", "banana"]
while (temp == 0):
    temp2 = random.choice(list_)
    print (temp2)

how do i make it not print the same fruit twice

EVAK
  • 13
  • 3
  • Does this answer your question? [How do I create a list of random numbers without duplicates?](https://stackoverflow.com/questions/9755538/how-do-i-create-a-list-of-random-numbers-without-duplicates) – Tomerikoo Jan 23 '22 at 14:32

2 Answers2

1

instead of using ranndom.choice, maybe use pop and shuffle:

list_ = ["apple", "orange", "banana"]
new_list= list_[:]
random.shuffle (new_list)
for i in range(3):
    print(new_list.pop())
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21
0

You can use random.sample with k=len(list_) to create a new list that has been shuffled:

>>> random.sample(list_, k=len(list_))
['banana', 'apple', 'orange']
dawg
  • 98,345
  • 23
  • 131
  • 206
  • The way the user has written this, I assume that the desire is to not alter the original list. It the original list CAN be altered, shuffle is preferred. – dawg Jan 23 '22 at 14:36
  • 1
    You are right on that -- sometimes fingers are faster than brain cells. – dawg Jan 23 '22 at 14:38