How do I iterate through combinations of a list

Question:

I have a list of elements, say

list = [1, 2, 3, 4]

and I would like to iterate through couples of distinct elements of this list, so

for x, y in some_iterator(list):
    print x, y

should show

1 2
1 3
1 4
2 3
2 4
3 4

Note that I don’t want all combinations of list as in this question. Just the combinations of a given length.

What would be the most pythonic way of doing this ?


What if I wanted to do the same with n-uples ? For instance with combinations of 3 elements out of n

for x, y, z in another_iterator(list):
    print x, y, z

would show

1 2 3
1 2 4
2 3 4
Asked By: usernumber

||

Answers:

Use itertools.combinations:

from itertools import combinations

for combo in combinations(lst, 2):  # 2 for pairs, 3 for triplets, etc
    print(combo)
Answered By: user2390182
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.