Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Python has a nice function in the standard library random.choice which returns a random element from a sequence. But none of the other languages I've developed in have thought to include such a feature. Do other languages provide such a feature? Why not?

share|improve this question
PHP has a built in function: array_rand() – rahmanisback Oct 22 '11 at 7:47
Ruby has Array#choice too: – Andy Waite Oct 22 '11 at 16:03
up vote 6 down vote accepted

When choosing features for standard libraries several things have to be taken into account.

One of them is how crucial or basic a given feature is. If it won't be used on a daily basis by a substantial group of users, it likely doesn't belong in a standard library. Every feature requires time and resources to design, implement, integrate and ensure quality of. Both are limited and have to be shared between all such would-be features. Finally, even assuming resources would be available, the bigger picture has to be taken into account. Standard libraries generally aim to provide a relatively minimal set of generic tools. Adding superfluous features causes a library to bloat, making it harder to use and maintain.

Standard library designers have to weigh all those qualities against each other. In case of this particular feature, some have made a decision for it, some against.

Even when the standard library doesn't provide this feature right of the bat, it can easily be implemented with little code. In typical cases it all boils down to choosing a random index in an array or sorting a collection using a random comparison function and returning the first/last element. It comes as no surprise that almost every language provides a random number generator and some generic sort function in its standard library.

A classic post by Eric Lippert that somewhat touches on the subject.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.