Fundamentals 5 min read

Three Simple Ways to Generate All 3‑Item Combinations in Python

This article walks through a fan's Python combination question, explains the combinatorial formula, and presents three practical implementations—including itertools, a custom index‑based approach, and a list‑comprehension with slicing—each verified with code output.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Three Simple Ways to Generate All 3‑Item Combinations in Python

1. Introduction

A fan asked how to generate all 3‑item combinations from a list of 10 Chinese character strings using Python. The combinatorial formula C(10,3)=120 confirms the expected number of combinations.

2. Solution Methods

Method 1 – itertools.combinations

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

Method 2 – Index‑based enumeration (image only)

This approach pre‑calculates the order of combinations before generating them.

Method 3 – List comprehension with slicing and index

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 above code uses three nested loops implemented via list comprehension, achieving the same 120 combinations.

Another explicit loop version demonstrates the same logic:

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)

3. Conclusion

The three methods successfully solve the fan's combination problem, each producing the expected 120 results. For small data sets, any method works, but using itertools.combinations is the most concise and efficient for larger inputs.

algorithmitertoolslist-comprehensioncombinations
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.