The simplest, direct way of consuming a list in a random fashion is painfully slow for list with a few 100's of elements. There are equally simple, but much faster ways to do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
from random import * data = range(10000) # the original, naive version def select(data): if data != : elem = choice(data) data.remove(elem) return elem else: return None # "final" version def select(data): if data != : pos = randrange( len(data) ) elem = data[pos] data[pos] = data[-1] del data[-1] return elem else: return None
The idea is to select a random element, but instead of deleting it (expensively copying the rest of the list frontwards), replacing it with the last element of the list (and deleting it later, which is cheap) As pointed by others, there are several ways to implement this idea, e.g., using it with a shallow copied list (in case you'll want to use all elements but also avoid deletions), or "sorting" the original list with random.shuffle(), but I prefer this simpler, more general approach.