4

say I have 3 different variables and each has 2 possible values, so in total I have 8 different combinations. Is there a python library function, or an algorithm that I can use to print all possible combinations?

Thanks

Yotam
  • 9,789
  • 13
  • 47
  • 68
  • possible duplicate of [Python code to pick out all possible combinations from a list?](http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list) – Matt Fenwick Aug 15 '12 at 11:55
  • @MattFenwick: No, this is not a combinations problem, rather it's the product the OP is looking for. – Martijn Pieters Aug 15 '12 at 12:01
  • 1
    possible duplicate of [Get the cartesian product of a series of lists in Python](http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python) – Martijn Pieters Aug 15 '12 at 12:02

2 Answers2

11

I think you're looking for product:

a = [1, 2]
b = [100, 200]
c = [1000, 2000]

import itertools
for p in itertools.product(a, b, c):
    print p

prints:

(1, 100, 1000)
(1, 100, 2000)
(1, 200, 1000)
(1, 200, 2000)
(2, 100, 1000)
(2, 100, 2000)
(2, 200, 1000)
(2, 200, 2000)
georg
  • 211,518
  • 52
  • 313
  • 390
1

And the true one function here is itertools.product

Odomontois
  • 15,918
  • 2
  • 36
  • 71