How do you find all permutations of a list with 3 elements in Python?
For example, input
[1, 2, 3, 4]
would return
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
Thanks!
How do you find all permutations of a list with 3 elements in Python?
For example, input
[1, 2, 3, 4]
would return
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
Thanks!
You want to use itertools.combinations
and a list comprehension:
>>> from itertools import combinations
>>> lst = [1, 2, 3, 4]
>>> [list(x) for x in combinations(lst, 3)]
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
>>>
Regarding your comment, you would make that list of strings by adding in str.join
and map
*:
>>> from itertools import combinations
>>> lst = [1, 2, 3, 4]
>>> [''.join(map(str, x)) for x in combinations(lst, 3)]
['123', '124', '134', '234']
>>>
*Note: You need to do map(str, x)
because str.join
requires an iterable of strings.