0

Say I have 4 arrays:

a = [1,2,3]
b = [1,2,3,4]
c = [1,2,3,4,5]
d = [1,2,3,4,5,6]

I could iterate like so:

tups = []

for i in a:
    for j in b:
        for k in c:
            for l in d:
                t = i,j,k,l
                tups.append(t)

tups would then be an array of tuples and will look something like this:

1,1,1,1
1,1,1,2
1,1,1,3
...
1,1,1,6
...

This seems rather long winded and I feel that there should be a faster/more efficient way of doing this, but I'm not really a python expert.

How can I make this faster, without looping over each array? Is there some functional approach which I can use?

pookie
  • 3,796
  • 6
  • 49
  • 105
  • Use [`itertools.combinations`](https://docs.python.org/2/library/itertools.html#itertools.combinations) – Barmar Sep 01 '17 at 23:18
  • @Barmar actually, this would be `itertools.product`. While `itertools.product` would be slightly faster, from an algorithmic complexity POV, it's just as inefficient anways. – juanpa.arrivillaga Sep 01 '17 at 23:20
  • Yeah, got confused between them. I remembered there was some itertools method for it. – Barmar Sep 01 '17 at 23:20
  • Please note, while this looks long-winded, that's because *it is*. What you want is the cartesian product, and that is fundamentally inefficient. – juanpa.arrivillaga Sep 01 '17 at 23:21

1 Answers1

0
In [1]: import itertools

In [2]: a=[1,2,3]

In [3]: b=[1,2,3,4]

In [4]: c=[1,2,3,4,5]

In [5]: d=[1,2,3,4,5,6]

In [6]: for i in itertools.product(a,b,c,d):
...:     print(repr(i))
...:     
(1, 1, 1, 1)
(1, 1, 1, 2)
(1, 1, 1, 3)
(1, 1, 1, 4)
(1, 1, 1, 5)
(1, 1, 1, 6)
(1, 1, 2, 1)
...
(3, 4, 5, 4)
(3, 4, 5, 5)
(3, 4, 5, 6)
zaufi
  • 6,811
  • 26
  • 34