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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With