-1

I have three arrays/lists:

list1 = range(1,10)
list2 = range(1,10)
list3 = range(1,10)

I want to create an list of tuples containing an assortment of each of the values in my three lists. Essentially I want an output such as:

combo = [(1,1,1), (1,1,2), (1,1,3) ... (1,4,2), (1,4,3) ... (4,5,4), (4,5,5) ... (10,10,9), (10,10,10)]

It seems like such as simple problem, but I don't know where to start.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Peter Li
  • 309
  • 3
  • 11
  • Are you looking for permutations/combinations of three for the numbers 1-10? – Zach Gates Mar 10 '15 at 20:52
  • 1
    Take a look at the `itertools` module https://docs.python.org/2/library/itertools.html#itertools.permutations – thumbtackthief Mar 10 '15 at 20:52
  • Just a heads up, `range(1,10)` will generate the numbers `1,2,3,...,7,8,9` -- 10 *will not* be included -- if you want that, you might change the end to 11. – jedwards Mar 10 '15 at 20:58

4 Answers4

3

You can use itertools.product to generate the Cartesian product of lists:

>>> import itertools
>>> list(itertools.product(list1, list2, list3))
[(1, 1, 1),
 (1, 1, 2),
 (1, 1, 3),
 (1, 1, 4),
 (1, 1, 5),
 (1, 1, 6),
 (1, 1, 7),
 (1, 1, 8),
 (1, 1, 9),
 (1, 2, 1),
 (1, 2, 2),
 (1, 2, 3)
 ...

itertools.product(list1, list2, list3) returns a generator object - only when you iterate over it will the tuples be returned. In the example code above, list is used to read the contents of the generator into a Python list.

Note that you can also use the repeat parameter of itertools which is much neater when your lists range over the same elements:

list(itertools.product(list1, repeat=3))
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
1

If I got it right, you want a Cartesian product of 3 lists? Well, there is a function for that in itertools

import itertools

result = list(itertools.product(list1, list2, list3))
Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
-1

You can also just create a list and append to it using nested loops. Just remember that if you also want the number 10, you need to change your range to range(1, 11) so that it stops at the number 11. It's like a < 11 (Doesn't include the number 11).

combo = []
for i in range(1, 11):
    for j in range(1, 11):
        for k in range(1, 11):
            a = (i, j, k)
            combo.append(a)
Zizouz212
  • 4,908
  • 5
  • 42
  • 66
-3

Use this :

combo=[]
for i in range(1,11):
  for j in range(1,11):
    for k in range(1,11):
      combo.append( (i,j,k) )
Aakash
  • 83
  • 1
  • 12