How can you select a random item from the list and delete it?

Let's say I have a list of colors colours = ['red', 'blue', 'green', 'purple'].
Then I want to call this python function that I hope exists random_object = random_choice(colours). Now, if random_object has "blue", I hope that colours = ['red', 'green', 'purple'].

Is there such a function in python?

+3
source share
2 answers

Firstly, if you want to delete it, because you want to do it again and again, you can use random.shuffle()in a random module.

random.choice() selects one but does not delete it.

Otherwise try:

import random

# this will choose one and remove it
def choose_and_remove( items ):
    # pick an item index
    if items:
        index = random.randrange( len(items) )
        return items.pop(index)
    # nothing left!
    return None
+7
source

one way:

from random import shuffle

def walk_random_colors( colors ):
  # optionally make a copy first:
  # colors = colors[:] 
  shuffle( colors )
  while colors:
    yield colors.pop()

colors = [ ... whatever ... ]
for color in walk_random_colors( colors ):
  print( color )
+6
source

Source: https://habr.com/ru/post/1766488/


All Articles