Is itertools combinations always sorted

Question:

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?

Asked By: Benny K

||

Answers:

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.

Answered By: user2357112
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.