How to generate all permutations of a list

0 votes

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([1])
[1]

permutations([1, 2])
[1, 2]
[2, 1]

permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
Nov 17, 2020 in Python by kartik
• 37,520 points
871 views

1 answer to this question.

0 votes

Hello @kartik,

Try this:

def permutations(head, tail=''):
    if len(head) == 0:
        print(tail)
    else:
        for i in range(len(head)):
            permutations(head[:i] + head[i+1:], tail + head[i])

called as:

permutations('abc')
answered Nov 17, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
0 answers

How to generate all permutations of a list?

How do you generate all the permutations ...READ MORE

Apr 26, 2022 in Python by Edureka
• 13,620 points
788 views
0 votes
1 answer

How to get permutations of list or a set in Python?

Permutation is an arrangement of objects in ...READ MORE

answered Jul 11, 2019 in Python by Neel
• 3,020 points
8,897 views
0 votes
1 answer

How to sort a list of strings?

Basic answer: mylist = ["b", "C", "A"] mylist.sort() This modifies ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,460 points
1,497 views
0 votes
1 answer

How to sort a list of strings?

Try  items = ["live", "like", "code", "cool", "bug"] ...READ MORE

answered Jul 27, 2018 in Python by Priyaj
• 58,020 points
844 views
0 votes
1 answer

How to make a flat list out of list of lists?

Hii @kartik, Given a list of lists l, flat_list = ...READ MORE

answered Apr 13, 2020 in Python by Niroj
• 82,840 points
655 views
0 votes
1 answer

How to unzip a list of tuples into individual lists?

Hello @kartik, zip is its own inverse! Provided you ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,840 points
1,906 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP