Home > Backend Development > Python Tutorial > How to Generate Combinations of Length n in Python?

How to Generate Combinations of Length n in Python?

Susan Sarandon
Release: 2024-11-16 04:58:03
Original
451 people have browsed it

How to Generate Combinations of Length n in Python?

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]
Copy after login

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)
Copy after login

This code outputs the expected result:

(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template