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!

1
  • Using for loops and slicing? Commented Nov 19, 2014 at 12:59

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)]

Comments

-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

1 Comment

This will produce the Cartesian product instead (e.g. you'll get (1,1) and (3,1) and (4,4)).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.