Is there a way to generate combinations, one at a time?

Question:

I can generate combinations from a list of numbers using itertools.combinations, such as the following:

from itertools import combinations

l = [1, 2, 3, 4, 5]

for i in combinations(l,2):
    print(list(i))

This generates the following:

[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 3]
[2, 4]
[2, 5]
[3, 4]
[3, 5]
[4, 5]

How can I generate just one of these list pairs at a time and save it to a variable? I want to use each pair of numbers, one pair at a time, and then go to the next pair of numbers. I don’t want to generate all of them at once.

Asked By: Alligator

||

Answers:

The itertools library actually returns a generator for most of it’s functions (including itertools.combinations()). You can read more about Generators here. Basically, it’s a function that lazily calculates values instead of generating everything all at once.

You can just get a single value out of a generator using the next command. Take a look at the following snippet:

import itertools

l = [1, 2, 3, 4, 5]

comb_generator = itertools.combinations(l, 2)

temp = next(comb_generator)  #Get the first combo into a var
print(temp)

#Do some other stuff

temp = next(comb_generator)  #Get another combo
print(temp)     

Whenever you want a new combination, you can get it by calling next() on your generator.

Answered By: Akilan Manivannan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.