26

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
user2390182
  • 72,016
  • 6
  • 67
  • 89
usernumber
  • 1,958
  • 1
  • 21
  • 58

1 Answers1

52

Use itertools.combinations:

from itertools import combinations

for combo in combinations(lst, 2):  # 2 for pairs, 3 for triplets, etc
    print(combo)
user2390182
  • 72,016
  • 6
  • 67
  • 89