One of the most fundamental topics in programming is combinatorics. Python has many built-in functions for permutations and combinations that are very useful when working with lists, strings, or other data types.
Python contains itertools package having direct methods for permutations and combinations. This article will go over how to use these functions to manipulate your data more effectively.
This blog post aims to teach you about Python permutations and combinations through interactive examples. We’ll start by exploring the difference between these two concepts before diving into the calculation.
Table of Contents
Python Permutations
Python Permutations are ordered arrangements. They can be considered ‘distinct’ lists since the order in which items appear matters, and repetition is forbidden: distinct from a set (which has no order).
In Python, there are many methods available to generate permutations. Here we will use the function by itertools package. First, we need to import the itertools package in Python.
Python Permutations of a String
import itertools
string = "CODE"
permutation = itertools.permutations(string)
for number in permutation:
print(*number)
Output

Python Permutation of Numbers
import itertools
integer = [2, 4, 6]
permutation = itertools.permutations(integer)
for number in permutation:
print(*number)
Output

Python Combinations
The python combination method takes a list and an input r as an input and returns the object list of tuples containing all possible length r combinations in a list form.
Python’s built-in function ‘combination’ returns the combination of elements without replacing sequence, but the python combination method returns combination with replacement.
The Python combination function requires two arguments, i.e., a list of elements and an input value telling how many values are to be picked for combination.
Python Combinations of a String
import itertools
string = "CODELEAKS"
combination = itertools.combinations(string, 3)
for number in combination:
print(*number)
Output

Python Combinations of Numbers
import itertools
integer = [20, 40, 60, 80]
combination = itertools.combinations(integer, 2)
for number in combination:
print(*number)
Output

Conclusion
Permutations refer to all possible orders a set of objects can be arranged into, while combinations refer to all possible subsets formed from a set. These two concepts are often confused, but it’s important not to mix these terms up when working with sets in the Python programming language. This article has discussed what permutations and combinations are, how they’re related with example codes for each concept, so you know how to use them appropriately!