Combinations of Length n
In programming, finding combinations is a common task. Combinations are sets of elements from a larger set that are chosen without repetition. For example, when choosing 3 numbers from the set [1, 2, 3, 4], the possible combinations are:
[1, 2, 3] [1, 2, 4] [1, 3, 4] [2, 3, 4]
Using the itertools Module
The Python itertools module provides a convenient way to generate combinations. The following code demonstrates how to use it to get all combinations of length n from a list of numbers:
import itertools for comb in itertools.combinations([1, 2, 3, 4], 3): print(comb)
This code outputs the expected result:
(1, 2, 3) (1, 2, 4) (1, 3, 4) (2, 3, 4)
The above is the detailed content of How to Generate Combinations of Length n in Python?. For more information, please follow other related articles on the PHP Chinese website!