0
How do I remove a random choice from a list after displaying it?
list1 = ['a', 'b', 'c', 'd', 'e', 'f'] import random print(random.choice(list1)) #Remove the random choice from list
4 Respostas
+ 1
print(list1.pop(list1.index(random.choice(list1))))
print(list1) #<--- just for you to see the result.
+ 5
rodwynnejones
Your solution will remove the left-most element when there are duplicate elements, causing a not perfectly random result.
JohnBovelle
import random
lst = ['a', 'b', 'c', 'd', 'e', 'f']
x = lst.pop(random.randrange(len(lst)))
print(x)
print(lst)
+ 2
@Diego
ahhhhhh.......I see what you mean now...thank you for point it out.
+ 1
@Diego
....put his list does not have duplicate elements.
....I ran your code (and my code) with duplicated elements.....and i cant see how your code output is any different to mine.
if duplicate elements is an issue, put the list into a set constructor, and put the set in a list constructor.