Fundamentals 5 min read

How to Generate All 3‑Item Combinations in Python Using itertools and List Comprehensions

This article explains a fan's request for a Python solution to a combinatorial problem, demonstrates three different implementations—including itertools.combinations, a custom index‑based method, and a list‑comprehension approach—and compares their outputs, concluding with a recommendation for the most efficient technique.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Generate All 3‑Item Combinations in Python Using itertools and List Comprehensions

1. Introduction

A fan asked for a Python solution to a basic permutation‑combination problem. The task is to compute the number of ways to choose 3 items from a list of 10, which mathematically equals C(10,3)=120.

2. Implementation

Method 1: Using itertools.combinations

from itertools import combinations
word = ['鲁班七号','鲁班','鲁班大师','甄姬','安琪拉','王昭君','韩信','孙悟空','程咬金','猪八戒']
res = [i for i in combinations(word, 3)]
print(res)
print(len(res))

The output shows 120 combinations, matching the manual calculation.

Method 2: Custom index‑based approach (illustrated in the image below)

This method also yields 120 combinations but requires pre‑computing the order of elements.

Method 3: List comprehension with slicing

word = ['鲁班七号','鲁班','鲁班大师','甄姬','安琪拉','王昭君','韩信','孙悟空','程咬金','猪八戒']
res = [[i, j, k] for i in word[:] for j in word[word.index(i)+1:] for k in word[word.index(j)+1:]]
print(res)
print(len(res))

The result image confirms 120 combinations.

Method 4: Explicit three‑level loop

res = []
for i in word[:]:
    for j in word[word.index(i)+1:]:
        for k in word[word.index(j)+1:]:
            res.append([i, j, k])
print(res)

The corresponding output again shows 120 combinations.

3. Conclusion

All three implementations correctly generate the 120 three‑item combinations, matching the manual calculation. For larger data sets, the itertools.combinations approach is recommended because it is concise and efficient.

Code examplesitertoolslist-comprehensioncombinatoricscombinations
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.