Python - How To Combinations of a List in Python

ID : 280

viewed : 179

Tags : PythonPython List

vote vote

100

A combination is a technique that determines the number of possible arrangements in a collection of elements. In a combination of elements, the elements are selected in an arbitrary order.

In this tutorial, we will find the total combinations of a list’s elements in Python.

Use the itertools.combinations() Function to Find the Combinations of a List in Python

The function combinations(list_name, x) from the itertools module takes the list name and a number x as the parameters and returns a list of tuples each of length x containing all the possible combinations of one element in the list with the other elements.

For example,

from itertools import combinations A = [10, 5, 'Hi'] temp = combinations(A, 2) for i in list(temp): 	print (i) 

Output:

(10, 5) (10, 'Hi') (5, 'Hi') 

A sorted list will output the combination tuples in sorted order. A combination of one element in the list with itself is not possible using the combinations() function.

Use the itertools.combinations_with_replacement() Function to Find the Combinations of a List in Python

The function combinations_with_replacement(list_name, x) from the itertools module takes the list name and a number ‘x’ as the parameters and returns a list of tuples each of length ‘x’ containing all possible combinations of the list’s elements. A combination of one element in the list with itself is possible using this function.

For example,

from itertools import combinations_with_replacement A = [1, 5, 'Hi'] temp = combinations_with_replacement(A, 2) for i in list(temp): 	print (i) 

Output:

(1, 1) (1, 5) (1, 'Hi') (5, 5) (5, 'Hi') ('Hi', 'Hi') 

Create a User-Defined powerset() Function to Find the Combinations of a List in Python

In mathematics, a power set of any set is a set which contains all the possible subsets of a given set along with an empty set. Power set of set S = {2, 5, 10} is {{}, {2}, {5}, {10}, {2, 5}, {2, 10}, {5, 10}, {2, 5, 10}}. The following function powerset() is used to loop through all the lengths ‘r’ of the list and print all the possible combinations of the list’s elements.

For example,

from itertools import chain, combinations def powerset(list_name):     s = list(list_name)     return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))  A = [60, 7, 'Hi'] for x in powerset(A):     print(x) 

Output:

() (1,) (5,) ('Hi',) (1, 5) (1, 'Hi') (5, 'Hi') (1, 5, 'Hi') 

  • Related HOW TO?