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:
-
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.
-
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