Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading