# Permutations and Combinations in Python with Examples

May 3, 2021

Permutations and Combinations of a set of elements are different arrangements of the elements of the set.

• Combination is a collection of the elements where the order doesn’t matter
• Permutation is an arrangement of a set where the order does matter.

Let’s consider a set as :

The permutations of the above set are as follows :

The combinations of the above set when two elements are taken together are :

In this tutorial, we will learn how to get the permutations and combinations of a group of elements in Python. We will look at sets of characters and numbers.

We will be using the combinations() and permutations() methods under the itertools module of Python.

Let’s get started.

## Permutations of Numeric data

To use the permutations() method under itertools module we will first need to import the module.

Now let’s define a set of numbers.

Now too get the list of permutations let’s use the permutations() method.

The line of code above gives an itertools object. To print the different permutations we will iterate over this object.

We get the output as :

The complete code for this section is given below :

## Permutations of a String

Next we will learn how to get the permutations of characters in a string.

We will be using the permutations() method, but this time we will pass a string as an argument.

Output :

## Permutations of fixed length

We can find permutations of a set where we only take a specified number of elements in each permutation. This is similar to nPr in the field of mathematics.

The code for finding permutations of fixed length is given below:

Output :

## Combinations of Numeric data

Just like the method permutations(), we can use combinations(), also under itertools to get the combinations of a set.

While calling combinations() we need to pass two arguments, the set for finding combinations of and a number that signifies the length of each combination.

Output :

## Combinations of a String

We can also get combinations of a string. To get the combinations of a string, use the following piece of code :

Output :

## Combinations with replacements

There is another method under the itertools module called combinations_with_replacement(). This method takes under consideration the combination of a number with itself as well.

Let’s see how it works.

### For numeric set

Output :

You can see the difference in the output above and the output for the operation of a normal combination. Here we have combinations like (1,1) and (2,2) which are not there in regular combinations operation.

Output :

## Conclusion

This tutorial was about finding permutations and combinations of a set in python. We used itertools module available in python to find the permutations and combinations.