itertools.combinations() module in Python to print all possible combinations

Given an array of size n, generate and print all possible combinations of r elements in array.


Input : arr[] = [1, 2, 3, 4],  
            r = 2
Output : [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve this problem in python using itertools.combinations() module.

What does itertools.combinations() do ?

It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.