How can I get all combinations (in order) of length n
from a list of numbers? For example, given the list [1, 2, 3, 4]
, and setting n = 3
, how can I get these results?
[1, 2, 3][1, 2, 4][1, 3, 4][2, 3, 4]
For combinations of all possible lengths, see Get all possible (2^N) combinations of a list’s elements, of any length . Note that this is not simply a matter of iterating over the possible lengths and combining the results, as there are other reasonable approaches to the problem.
To avoid duplicate outputs when the input has duplicate elements, see Python combinations without repetitions .
Also related: Generate all binary strings of length n with k bits set