Search code examples
pythonrandomsimulationsampling

Random sampling simulation in python


Problem: Assume we have a list of members' IDs: [1,2,3,4,5,6,7,8,9,10,....] I need to run 1000 simulations drawing teams of size 4 at random from all members without replacement. (drawn uniformly at random without replacement from all members)

Output: The final result should be 1000 teams with size of 4.

Thanks


Solution

  • You are looking for random.sample(population, k):

    Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

    >>> import random
    >>> players = [1,2,3,4,5,6,7,8,9,10]
    >>> teams = [random.sample(players, 4) for _ in range(1000)]
    >>> teams[0]
    [8, 4, 5, 10]