Python one-liner to print permutations of a string I have written a Python one-liner that permutes a given string. I wrote this just for fun using list comprehensions and I would like to get feedback from the community.

def permute(c, s=""):
    return [s] if len(s) == len(c) else [x for y in [permute(c, e) for e in [s[0:i]+c[len(s)]+s[i:] for i in xrange(len(s)+1)]] for x in y]

print permute ("omer")
Even though the code fits a single line, this is not Pythonic. Just because Python allows to put a lot of things on a single line because of list comprehensions, ternary operators and other syntactic sugar, it does not mean you have to try making your code as short as possible. Remember the Zen of Python, in particular:


  Explicit is better than implicit.
  
  Flat is better than nested.
  
  Readability counts.
  
  If the implementation is hard to explain, it's a bad idea.


Expand the solution into multiple lines using meaningful variable names and comments:

def permute(c, s=""):
    """Returns all possible permutations of a string c."""
    if len(s) == len(c):  # base case - returns a single variation of a string - string itself
        return [s]
    else:
        variations = [s[0:i] + c[len(s)] + s[i:] for i in range(len(s) + 1)]

        # get all permutations for each variation of a string
        permutations = [permute(c, e) for e in variations]

        # flatten a list of lists
        return [x for y in permutations for x in y]

print(permute("omer"))