VOOZH about

URL: https://www.geeksforgeeks.org/python/permutation-and-combination-in-python/

⇱ Permutation and Combination in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Permutation and Combination in Python

Last Updated : 23 Jul, 2025

Python provides built-in methods to work with permutations and combinations using the itertools module. These are helpful in problems involving arrangement (order matters) and selection (order doesn’t matter) of elements.

Let's explore them one by one:

Permutation

A permutation is an arrangement of elements where the order matters. For example, (1, 2) and (2, 1) are two different permutations.
Python offers the permutations() method in the itertools module to generate these.

Example 1: Get All Permutations of a List


Output
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

Explanation:permutations([1, 2, 3]) returns all possible orderings (3! = 6 permutations).

Example 2: Permutations of Specific Length

We can also generate permutations of a specific length r.


Output
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)

Explanation:permutations([1, 2, 3], 2) returns 2-length ordered arrangements (nPr = 6).

Combination

A combination is a way to select elements where the order does not matter. For example, (1, 2) and (2, 1) are considered the same combination.
Python offers the combinations() method for this purpose.

Example 1: Get All Combinations of Length 2


Output
(1, 2)
(1, 3)
(2, 3)

Explanation:

  • combinations([1, 2, 3], 2) returns all 2-element subsets without regard to order.
  • Duplicates are avoided (e.g., (2,1) is not separate from (1,2)).

Example 2: Combinations from an Unsorted List 


Output
(2, 1)
(2, 3)
(1, 3)

Explanation:

  • combinations([2, 1, 3], 2) preserves the input order in output combinations.
  • Elements are treated uniquely based on their position in the list.

Example 5: Combinations with Repetition

Use combinations_with_replacement() to allow repeated elements in combinations.


Output
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)

Explanation: combinations_with_replacement([1, 2, 3], 2) includes combinations like (1, 1), allowing repetition.

Related articles:

Comment
Article Tags:
Article Tags: