Search code examples
pythonpython-itertools

Take n items at random from a list


I have a list L and want to return a list of n items from it, at random.

Right now I am relying on itertools.combinations and then picking one at random, but I have to wait a while until the list looks like something that isn't stuck with a lot of items near the start of the list, so it's not really "random."


Solution

  • use random.sample to sample K items from a list of population n.

    >>> import random
    >>> random.sample(range(100), 5)
    [56, 1, 0, 60, 61]