Search code examples
pythoncombinationspython-itertools

Get all ordered combinations of list python


I'm trying to generate all n-item combinations of a list of numbers while maintaining numerical order. So for example, if the list were

[1,2,3,4]

The ordered combinations of length 3 would be:

[1,2,3]
[2,3,4]
[1,2,4]
[1,3,4]

To be clear, I have to maintain numerical order, so [1,4,2] would not be a desired outcome.

Is there a function that does this, or a fast algorithm that would get it done? The actual list is 111 and I will be choosing 100 items. Thanks.


Solution

  • Are you just looking for all the combinations of a given list of length n? If so you can just use combinations from itertools. Either way you'll probably want to go with itertools.

    from itertools import combinations
    
    numbers = [1,2,3,4]
    for item in combinations(numbers, 3):
        print sorted(item)