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

23rd Nov 2019, 7:37 PM
Steven Iannucci
Steven Iannucci - avatar
4 Respostas
+ 1
print(list1.pop(list1.index(random.choice(list1)))) print(list1) #<--- just for you to see the result.
23rd Nov 2019, 8:12 PM
rodwynnejones
rodwynnejones - avatar
+ 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)
23rd Nov 2019, 8:36 PM
Diego
Diego - avatar
+ 2
@Diego ahhhhhh.......I see what you mean now...thank you for point it out.
23rd Nov 2019, 10:33 PM
rodwynnejones
rodwynnejones - avatar
+ 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.
23rd Nov 2019, 10:07 PM
rodwynnejones
rodwynnejones - avatar