3

How do I iterate over all pair combination in a list, like:

list = [1,2,3,4]

Output:

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

Thanks!

moti
  • 159
  • 4

3 Answers3

4

Use itertools.combinations:

>>> import itertools
>>> lst = [1,2,3,4]
>>> for x in itertools.combinations(lst, 2):
...     print(x)
...
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

BTW, don't use list as a variable name. It shadows the builtin function/type list.

falsetru
  • 357,413
  • 63
  • 732
  • 636
1

Use itertools.combinations

>>> import itertools
>>> list(itertools.combinations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
-2

You can use a nested for loop as follows:

list = [1,2,3,4]
for x in list :

    for y in list :

        print x, y
stang
  • 311
  • 3
  • 12
  • 3
    This will produce the Cartesian product instead (e.g. you'll get (1,1) and (3,1) and (4,4)). – DSM Nov 19 '14 at 13:02