Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over every two elements in a list in Python [duplicate]

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!

like image 554
moti Avatar asked Jun 07 '26 01:06

moti


1 Answers

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.

like image 116
falsetru Avatar answered Jun 08 '26 13:06

falsetru