user8920020
user8920020

Reputation:

How can I create combinations of elements in a list one by one?

I have a list of elements [1, 2, 3, 4, 5], I want to generate combinations one by one, like [1, 2, 3], [2, 4, 5], etc.

I tried using itertools.combinations but that makes a list of all possible combinations, which takes up too much memory space.

How do I access each new combination right when it is generated?

Upvotes: 0

Views: 38

Answers (1)

Robᵩ
Robᵩ

Reputation: 168586

How do I access each new combination right when it is generated?

Use a for loop, like so:

import itertools
for a, b, c in itertools.combinations(range(1, 101), 3):
    if a**2 + b**2 == c**2:
        print(a, b, c)

itertools.combinations makes a list of all possible combinations

No, it doesn't.

itertools.combinations() is a generator function. When used in a for loop, only one result is returned at a time. No list of all the results is ever created.

Upvotes: 2

Related Questions