Get All Possible Combinations from a List using Python

Problem

Have you ever needed to get all possible combinations from a list?

Solution

You can do this pretty easily using Python using itertools.

See this script below in which we are taking a list from an array, getting all the possible combinations using itertools, writing that output to a data frame using pandas, and then printing that data frame to an excel file using pyexcel.

Tools

  • Python
  • Excel

Script

from itertools import combinations
import pandas as pd
import openpyxl

sample_list = ['apple','orange','banana','pear']

list_combinations = list()
for n in range(len(sample_list) + 1):
list_combinations += list(combinations(sample_list, n))

data = {'data':list_combinations}

df = pd.DataFrame(data, columns = ['data'])

df.to_excel(r"C:\Users\prati\OneDrive\Documents\Vertical.xlsx")
print(df)

Output

data
0 ()
1 (apple,)
2 (orange,)
3 (banana,)
4 (pear,)
5 (apple, orange)
6 (apple, banana)
7 (apple, pear)
8 (orange, banana)
9 (orange, pear)
10 (banana, pear)
11 (apple, orange, banana)
12 (apple, orange, pear)
13 (apple, banana, pear)
14 (orange, banana, pear)
15 (apple, orange, banana, pear)