1

I have a list made of strings which are not in sorted order. I wish to generate combinations but in such a way that the order of the elements is as in the list. However, Python documentation and its behavior confuses me. To quote:

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

  2. Elements are treated as unique based on their position, not on their value. If the input elements are unique, there will be no repeated values within each combination.

I experimented a little and found the following behavior in Python 3.12.4:

>>> [c for c in combinations([7,3,4],2)]
[(7, 3), (7, 4), (3, 4)]

>>> [c for c in combinations({7,3,4},2)]
[(3, 4), (3, 7), (4, 7)]

While the first outcome that uses a list solves by purpose, it seems to contradict the documentation and may not be reliable. The second outcome that uses sets, however, is consistent with the documentation but does not serve my purpose.

I would be grateful for any clarification on these observations.

PS: I understand that the problem can be solved using additional list comprehension, but I would like to avoid it if that step is not required.

8
  • Why do you think the first one contradicts the documentation? They are in the order of the input iterable and is what you want. Commented Jul 17, 2024 at 20:46
  • Because the 1st says 'lexicographic order' and not the 'input order'. Commented Jul 17, 2024 at 20:48
  • 4
    “ Lexicographic order according to the order of the input iterable”. The input order defines the lexicographic sequence Commented Jul 17, 2024 at 20:52
  • 2
    In your second test you used a set rather than list. Sets don't have any order, so you get unpredictable results. Commented Jul 17, 2024 at 20:53
  • @MarkTolonen, how is the order of input different from the lexicographic order? If so IMHO, Pt.1 is redundant due to Pt.2. Commented Jul 17, 2024 at 20:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.