This is a simple Python implementation:
from random import random
def select(container, weights):
total_weight = float(sum(weights))
rel_weight = [w / total_weight for w in weights]
# Probability for each element
probs = [sum(rel_weight[:i + 1]) for i in range(len(rel_weight))]
slot = random()
for (i, element) in enumerate(container):
if random()slot <= probs[i]:
break
return element
and
population = ['apple','orange','lemon']
weights = [4, 2, 1]
print select(population, weights)
In genetic algorithms this select procedure is called Fitness proportionate selection or Roulette Wheel Selection since:
- a proportion of the wheel is assigned to each of the possible selections based on their weight value. This can be achieved by dividing the weight of a selection by the total weight of all the selections, thereby normalizing them to 1.
- then a random selection is made similar to how the roulette wheel is rotated.

Typical algorithms have O(N) or O(log N) complexity but you can also do O(1) (e.g. Roulette-wheel selection via stochastic acceptance).