Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

How do you generate all the permutations of a list in Python, independently of the type of elements in that list?

For example:

permutations([])

[]

permutations([5])

[5]

permutations([1, 5])

[1, 5]

[5, 1] 

permutations([1, 5, 7])

[1, 5, 7]

[1, 7, 5]

[5, 1, 7]

[5, 7, 1]

[7, 1, 5]

[7, 5, 1]

2 Answers

0 votes
by (260 points)
edited by

You can use the itertools module.

import itertools

permutations = itertools.permutations(my_list, len(my_list))

and loop over the permutations object to get the lists you want :

for p in permutations:

l = list(p)

0 votes
by (106k points)

You can use the bellow-mentioned code to generate the permutations of list in Python:-

def permutations(head, tail=''):

    if len(head) == 0: print tail

    else:

      for i in range(len(head)):

        permutations(head[0:i] + head[i+1:],  tail+head[i])

The caller code is as follows:-

permutations('abc')

To know more about this you can have a look at the following video tutorial:-

Related questions

Browse Categories

...