Ele
Ele

Reputation: 563

python limit itertools result

I'm using itertools to get all combinations of a list:

import itertools

stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for L in range(0, len(stuff)+1):
  for subset in itertools.combinations(stuff, L):
    print(subset)

Is there a way to limit the result to e.g. combinations with at least 2 and at most 5 elements?

Thanks!

Upvotes: 2

Views: 480

Answers (2)

Oleksii Filonenko
Oleksii Filonenko

Reputation: 1653

Just change the for loop.

import itertools

stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for L in range(2, 6):
  for subset in itertools.combinations(stuff, L):
    print(subset)

Upvotes: 4

Moses Koledoye
Moses Koledoye

Reputation: 78564

Limit the range to [2, 6):

for L in range(2, 6):
   for subset in itertools.combinations(stuff, L):
      print(subset)

Upvotes: 8

Related Questions