elseres [for in range(len(seq))rest seq[:iseq[ + :for in permute (rest)res append(seq[ : + xreturn res def permute (seq)if not seqyield seq elsefor in range(len(seq))rest seq[:iseq[ + :for in permute (rest)yield seq[ : + empty sequence delete current node permute the others add node at front shuffle any sequencegenerator empty sequence delete current node permute the others add node at front both of these functions produce the same resultsthough the second defers much of its work until it is asked for result this code is bit advancedespecially the second of these functions (and to some python newcomers might even be categorized as cruel and inhumane punishment!stillas 'll explain in momentthere are cases where the generator approach can be highly useful study and test this code for more insightand add prints to trace if it helps if it' still mysterytry to make sense of the first version firstremember that generator functions simply return objects with methods that handle next operations run by for loops at each leveland don' produce any results until iteratedand trace through some of the following examples to see how they're handled by this code permutations produce more orderings than the original shuffler--for itemswe get (factorialresults instead of just ( for in factthat' why we need recursion herethe number of nested loops is arbitraryand depends on the length of the sequence permutedfrom scramble import scramble from permute import permute permute list(scramble('abc')['abc''bca''cab'simple scramblesn permute ('abc'['abc''acb''bac''bca''cab''cba'list(permute ('abc')['abc''acb''bac''bca''cab''cba'permutations largerng permute ('abc'next( 'abcnext( 'acbfor in permute ('abc')print(xprints six lines iterate (iter(not neededgenerate all combinations automatic iteration generator functions and expressions