Home > Software design >  Is itertools combinations always sorted
Is itertools combinations always sorted

Time:12-20

Suppose I have sorted array from which I want to get all itertools.combinations of, say, 3 elements.

from itertools import combinations
start = 5
end = start 4
some_pos_number = 3
inds = list(combinations(range(start,end),some_pos_number))

>>>inds
[(5, 6, 7), (5, 6, 8), (5, 7, 8), (6, 7, 8)]

Is all of these combinations will always be sorted?

CodePudding user response:

Quoting the docs:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the output tuples will be produced in sorted order.

So the individual combinations will be internally sorted (being subsequences of a sorted iterable), and the sequence of combinations will itself be sorted too.

  • Related