Search code examples
pythonrandomcombinationspython-itertools

Difference between random.sample(sample,k) and itertools.combinations(p,r)


Hello I am new to python, and have just started writing basic python scripts. I have decided to write a password generator program. I came across random.sample() and itertools.combinations() functions. And I would like to know the difference between them. I have read the documentation and came to the following conclusion:
1. random.sample() will return a list of unique combination from the population provided there r no repeated values in the population.
2. combinations() will also return a tuple of (p,r) possible combinations where r is the length. and there was this line,"Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination." which i didn't understand. I assume it says that input elements must be unique to get unique combinations

So i came to final conclusion that both are same. I would like to know whether i am right or wrong (with explanations pls). Thank you.


Solution

  • They are not the same, actually they do completely different things. itertools.combinations() is a generator - it returns a sequence of all combinations from a given set of values. random.sample() provides one (randomly selected) combination. Run these two snippets:

    import random
    print(random.sample([1,2,3], 2))
    

    and

    import itertools
    for c in itertools.combinations([1,2,3],2):
        print(c)
    

    and note the difference.