# itertools.combinations() in Python

In this tutorial, we are going to learn about **itertools.combinations()** in Python. Firstly, let’s get an idea of itertools.combinations(). Itertools is a module in Python that provides various functions that work on iterators. Meanwhile, combinations() is a function in Python.

## Combinations() in Python

This iterator (function) takes two parameters as input simultaneously. They are iterable, and r(required length). This function prints all the possible combinations of the iterator with the specified length (r). This function is similar to the concept of **Combinations **which you have learned in your high school math. Let’s see an example of combinations. We have to import combinations function from the itertools module in our code.

Example:-

from itertools import combinations a = combinations('12345', 2) print(a)

Output:-

<itertools.combinations object at 0x000001D7AE5091D8>

The output of the combinations class is itertools.combinations() object. So, we got its object as a result. Now we will extract it using the list. In the above example **‘12345’ **is an iterable and **2 ** is the length of the combinations(r).

from itertools import combinations a = combinations('12345', 2) print(list(a))

Output:-

[('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]

So, as a result, we are getting the output that consists of all the combinations of tuples in a list. If we observe the output the tuples in the list are in sorted order. Because, as the iterator in the input is also in sorted order. Let’s see an example with unsorted input.

Example:-

from itertools import combinations a = list(combinations('5713', 3)) print(a)

Output:-

[('5', '7', '1'), ('5', '7', '3'), ('5', '1', '3'), ('7', '1', '3')]

In the above example, we got the list of unsorted tuples as a result. To sort the list just use the sorted function.

print(sorted(a))

Output:-

[('5', '1', '3'), ('5', '7', '1'), ('5', '7', '3'), ('7', '1', '3')]

Here the list is in sorted order.

Also, read:- Generating All Permutations In Python

## Leave a Reply

You must be logged in to post a comment.