/    Sign up×
Bounties /Pin to ProfileBookmark

How to get all the permutations of a list in Python?

For example, if the input is [1,2], then it returns [1,2] and [2,1].

to post a answer
Python

1 Replies

Copy linkTweet thisAlerts:
@PhysBoomAug 31.2022 — You can simply use the itertools library, i.e.


import itertools

lst = [1, 2, 3]
print(list(itertools.permutations(lst)))


would print


[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]


Or, if you want to return a list of lists instead of a list of tuples as posed in the question:


import itertools

def get_permutations(lst):
return ([list(permutation) for permutation in itertools.permutations(lst)])

print(get_permutations([1,2,3]))


Would print


[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
×

Success!

Help @MichaelDelgado spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...