I always wondered how a programmer could efficiently generate a random number from a set* of numbers once and only once.

I quickly realized the inefficient solution. Simply generate the number and if it equals one you have all ready generated then regenerate the number.

Regenerating the number is a poor method. Especially in a small set or if you are going to exhaust the elements in the set.

Today I realized a smarter solution. Instead of using random to generate a number that is in the set, use random to generate the index of a element in the set and then return that value and remove the element from the set.

Now I'm just wondering what the best way to implement this is.

It would be relatively simple to implement it in a function, but part of the procedure is modifying the list in question. Python documentation labels modifying lists within a function as a bad practice. I just don't understand why. I also can't understand how to get around this either at the moment.

* By set, I don't necessarily mean Python's built in set object. This would probably be implemented using a mutable sequence.

*Edited
by lrh9*: n/a