0
votes

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?

1
Iterate through list(itertools.combinations(a,3)) where a = [1,2,3,4,5] - Sruthi V
Do you want to use generator? - Zhiya
But itertools.combinations is a generator, thus there shouldn't be a memory problem? - datasailor
myList = [1, 2, 3, 4, 5]. list(itertools.combinations(myList, 3)) gives me a list of combinations, [1, 2, 3], [2, 3, 4], ... , [3, 4, 5]. This works fine for small myLists, but for a list with thousands of combinations it takes up a lot of memory space and time. I want to check if each combination of numbers can make a valid triangle. So I want to generate one combination, check it, and stop if it fits, instead of making a list of all the combinations and then checking them. - user8920020

1 Answers

2
votes

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.