tags:

views:

89

answers:

3

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

Does such a function exist in python?

A: 

You have to write your own function to do this using random module

Something like this:

import random
colors = ['red', 'blue', 'green', 'purple']


def colorRandom(colors):
    x = random.randrange(0, len(colors))
    print colors
    color = colors[x]
    colors.remove(color)
    return color , colors


color, colors = colorRandom(colors)
print color
print colors

color, colors = colorRandom(colors)
print color
print colors

Output:

['red', 'blue', 'green', 'purple']
blue
['red', 'green', 'purple']
['red', 'green', 'purple']
red
['green', 'purple']

You can improve this by other nifty python features like lambda ...

pyfunc
+3  A: 

Firstly, if you want it removed because you want to do this again and again, you might want to use random.shuffle() in the random module.

random.choice() picks one, but does not remove 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
Russell Borogove
+1  A: 

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 )
flow
Upvoted for a nice use of generators.
Russell Borogove