Itertools Product Combinations Permutations
itertools.product expands several iterables into the cartesian product, combinations picks unordered subsets, permutations keeps order.
Code
from itertools import combinations, permutations, product
# product:笛卡尔积——每个输入序列各取一个,穷举所有搭配
sizes = ["s", "m"]
colors = ["red", "blue"]
print("product:", list(product(sizes, colors)))
# repeat= 把单个序列与自身做 n 次笛卡尔积:两颗骰子的点数组合
print("dice:", list(product(range(1, 7), repeat=2))[:4], "...")
# combinations:组合无序,同一组元素只出现一次
print("combinations:", list(combinations("abc", 2)))
# permutations:排列有序,同样的输入数量是组合的两倍
print("permutations:", list(permutations("abc", 2)))
print("counts: 2-pick", len(list(combinations("abc", 2))), "2-perm", len(list(permutations("abc", 2))))Output
Captured from a sandboxed run of this snippet in the build pipeline.
product: [('s', 'red'), ('s', 'blue'), ('m', 'red'), ('m', 'blue')]
dice: [(1, 1), (1, 2), (1, 3), (1, 4)] ...
combinations: [('a', 'b'), ('a', 'c'), ('b', 'c')]
permutations: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
counts: 2-pick 3 2-perm 6How it works
product(sizes, colors) builds the full Cartesian product — one element from each input per tuple, two sizes times two colors, yielded in input order. repeat=2 multiplies one sequence by itself, which is how the dice line enumerates two-dice rolls from a single range(1, 7) before the ellipsis prints only the first four tuples. combinations('abc', 2) emits unordered pairs — ('a','b') appears once and ('b','a') never does — while permutations('abc', 2) treats order as significant and yields both; the closing len(...) calls print the two counts side by side, 3 combinations versus 6 permutations.
What to watch for
- No external surface: all behavior comes from the standard library.
One line does most of the work here:
colors = ["red", "blue"]
A line that quietly does half the work:
sizes = ["s", "m"]
Interactive Tools for This Topic
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `itertools`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.