# Python – Itertools.Combinations_with_replacement()

• Difficulty Level : Expert
• Last Updated : 26 Aug, 2022

Itertools in Python refers to module provided in Python for the creation of iterators which helps in efficient looping, time and space efficiency as well. Itertools helps us to solve complex problems easily and efficiently. There are in general 3 types of iterators.
Different types of iterators provided by this module are:

## Itertools.Combinations_with_replacement()

Itertools.Combinations_with_replacement() lies in the Combinatoric Generator subtype of itertools. Combinatoric generators refer to those iterators which deal with the different arrangements possible for an iterator. Here the elements are referred with there index value and not by their value or type.
How to use Itertools.Combinations_with_replacement() function?
As understood by name “combinations” means all the possible subsets or arrangements of the iterator and the word “combinations_with_replacement” means all the possible arrangements or subsets that allow an element to repeat in a subset. This function takes ‘r’ as input here ‘r’ represents the size of different combinations that are possible. All the combinations with repetition of elements are emitted and are of length ‘r’ and ‘r’ is a necessary argument here.
Example 1:-

## Python3

 `from` `itertools ``import` `combinations_with_replacement`  `a ``=``"GEeks"` `l ``=` `list``(combinations_with_replacement(a, ``2``))``print``(``"COMBINATIONS WITH REPLACEMENTS OF STRING GEeks OF SIZE 2."``)``print``(l)`

Output:-

COMBINATIONS WITH REPLACEMENTS OF STRING GEeks OF SIZE 2.
[(‘G’, ‘G’), (‘G’, ‘E’), (‘G’, ‘e’), (‘G’, ‘k’), (‘G’, ‘s’), (‘E’, ‘E’), (‘E’, ‘e’), (‘E’, ‘k’), (‘E’, ‘s’), (‘e’, ‘e’), (‘e’, ‘k’), (‘e’, ‘s’), (‘k’, ‘k’), (‘k’, ‘s’), (‘s’, ‘s’)]

Example 2:-

## Python3

 `from` `itertools ``import` `combinations_with_replacement``  ` `      ` `print` `(``"All the combination of List in sorted order(with replacement) is:"``)  ``print``(``list``(combinations_with_replacement(``'D.P.S.'``, ``2``)))  ``print``()  `  `print` `(``"All the combination of list in sorted order(with replacement) is:"``)  ``print``(``list``(combinations_with_replacement(``range``(``1``, ``5``), ``2``)))`

Output:-

All the combination of List in sorted order(with replacement) is:
[(‘D’, ‘D’), (‘D’, ‘.’), (‘D’, ‘P’), (‘D’, ‘.’), (‘D’, ‘S’), (‘D’, ‘.’), (‘.’, ‘.’), (‘.’, ‘P’), (‘.’, ‘.’), (‘.’, ‘S’), (‘.’, ‘.’), (‘P’, ‘P’), (‘P’, ‘.’), (‘P’, ‘S’), (‘P’, ‘.’), (‘.’, ‘.’), (‘.’, ‘S’), (‘.’, ‘.’), (‘S’, ‘S’), (‘S’, ‘.’), (‘.’, ‘.’)]
All the combination of list in sorted order(with replacement) is:
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]

My Personal Notes arrow_drop_up