Is there a pythonic way of permuting a list of list?
<p>I have a list of lists containing unique strings and I want to produce an arbitrary number of different ways of sorting it. The list might look like the following:</p>

<pre><code>list = [[a], [b,c], [d], [e,f,g]]
</code></pre>

<p>The order of the lists need to be the same but I want to shuffle the ordering within a list and then have them in a single list, e.g</p>

<pre><code>list1 = [a,b,c,d,e,f,g]
list2 = [a,c,b,d,f,e,g]
...
...
listN = [a,c,b,d,f,g,e]
</code></pre>

<p>What is a good pythonic way of achieving this? I'm on python 2.7.</p>

<p>You can do this by taking the Cartesian product of the permutations of the sub-lists, and then flattening the resulting nested tuples. </p>

<pre><code>from itertools import permutations, product, chain

lst = [['a'], ['b', 'c'], ['d'], ['e', 'f', 'g']]

for t in product(*[permutations(u) for u in lst]):
    print([*chain.from_iterable(t)])
</code></pre>

<p><strong>output</strong></p>

<pre><code>['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'g', 'f']
['a', 'b', 'c', 'd', 'f', 'e', 'g']
['a', 'b', 'c', 'd', 'f', 'g', 'e']
['a', 'b', 'c', 'd', 'g', 'e', 'f']
['a', 'b', 'c', 'd', 'g', 'f', 'e']
['a', 'c', 'b', 'd', 'e', 'f', 'g']
['a', 'c', 'b', 'd', 'e', 'g', 'f']
['a', 'c', 'b', 'd', 'f', 'e', 'g']
['a', 'c', 'b', 'd', 'f', 'g', 'e']
['a', 'c', 'b', 'd', 'g', 'e', 'f']
['a', 'c', 'b', 'd', 'g', 'f', 'e']
</code></pre>

<p>If you need to do this in Python 2, you can replace the print line with this: </p>

<pre><code>print list(chain.from_iterable(t))
</code></pre>

<hr>

<p>Here's a more compact version, inspired by ewcz's answer:</p>

<pre><code>for t in product(*map(permutations, lst)):
    print list(chain.from_iterable(t))
</code></pre>

python list python-2.7 permutation