Permutations of a list using stack
<p>I'm trying to find a way to enumerate all combinations of a list of numbers without recursion or using itertools.  I came up with a solution that works but I think it turned into a recursive function after all.  I'm new to Python and not sure how I would make this work without recursion.</p>

<p>Any help is appreciated as I think I'm still failing to see the difference between the two.</p>

<pre><code>result = []

def permutation(li):
    if len(li) == 1:
        result.append(li[0])
        print (result)
        result.pop()
        return

    for i in range(0,len(li)):
        result.append(li[i])
        permutation(li[:i] + li[i+1:])
        result.pop()    

permutation([1,2,3])
</code></pre>

<p>It is not that intuitive to come up with an algorithm "just like that" that produces all permutations without the use of recursion. </p>

<p>But there exist several different such algorithms. Have look at <a href="https://en.wikipedia.org/wiki/Heap%27s_algorithm" rel="nofollow">Heap's algorithm</a> for example:</p>

<pre><code>def permutation(li):
    n = len(li)
    c = [0] * n

    print(li)
    i = 1
    while i &lt; n:
        if c[i] &lt; i:
            j = c[i] if i % 2 else 0
            li[j], li[i] = li[i], li[j]
            print(li)
            c[i] += 1
            i = 1
        else:
            c[i] = 0
            i += 1
</code></pre>

python algorithm