How to generate all permutations of a list in Python

Answer

If you're using an older Python (<2.6) for some reason or are just curious to know how it works, here's one nice approach, taken from http://code.activestate.com/recipes/252178/:

def all_perms(elements):if len(elements)<=1:yield elements
    else:for perm in all_perms(elements[1:]):for i in range(len(elements)):# nb elements[0:1] works in both string and list contextsyield perm[:i]+ elements[0:1]+ perm[i:]

All python Questions

Ask your interview questions on python

Write Your comment or Questions if you want the answers on python from python Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---