How to get every single permutation of a string?
Question: I know how to get the permutations of just the plain string in python:

    
    
    >>> from itertools import permutations
    >>> perms = [''.join(p) for p in permutations('stack')]
    >>> print perms
    ...
    

But how would I get the permutations of `'stac'`, `'stak'`, `'sack'`,
`'stck'`, `'stc'`, `'st'`, and so forth? My desired output is:

    
    
    >>> permutations('pet')
    ['pet', 'pte', 'ept', 'etp', 'tpe', 'tep', 'pe', 'ep', 'p', 'e', 't', 'pt', 'tp', 'et', 'te']
    

What I have so far:

    
    
    def permutate(values, size):
      return map(lambda p: [values[i] for i in p], permutate_positions(len(values), size))
    
    def permutate_positions(n, size):
      if (n==1):
        return [[n]]
      unique = []
      for p in map(lambda perm: perm[:size], [ p[:i-1] + [n-1] + p[i-1:] for p in permutate_positions(n-1, size) for i in range(1, n+1) ]):
        if p not in unique:
          unique.append(p)
      return unique
    
    def perm(word):
      all = []
      for k in range(1, len(word)+1):
         all.append(permutate([' ']+list(word), k))
      return all
    

This runs as:

    
    
    >>> perm('pet')
    [[['t'], ['e'], ['p']], [['t', 'e'], ['e', 't'], ['e', 'p'], ['t', 'p'], ['p', 't'], ['p', 'e'], ['p', 'p']], [['t', 'e', 'p'], ['e', 't', 'p'], ['e', 'p', 't'], ['e', 'p', 'p'], ['t', 'p', 'e'], ['p', 't', 'e'], ['p', 'e', 't'], ['p', 'e', 'p'], ['t', 'p', 'p'], ['p', 't', 'p'], ['p', 'p', 't'], ['p', 'p', 'e']]]
    >>> 
    

However, it has a bunch of list of lists, and with values like ['p', 'p',
't']!

How do I do this? ANy help is appreciated.


Answer: This is one way of doing it with
[itertools.permutations](https://docs.python.org/2.7/library/itertools.html#itertools.permutations):

    
    
    from itertools import permutations
    s = 'pet'
    print [''.join(p) for i in range(1, len(s)+1) for p in permutations(s, i)]
    

Output:

    
    
    ['p', 'e', 't', 'pe', 'pt', 'ep', 'et', 'tp', 'te', 'pet', 'pte', 'ept', 'etp', 'tpe', 'tep']
    

