Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all possible sequences of elements in a list?

Tags:

python

I have a list [2,3,4]. How do I find all possible sequence of elements in the list? So the output should be: [2,3,4] [2,4,3] [3,2,4] [3,4,2] [4,2,3] [4,3,2]

like image 742
Bruce Avatar asked Jan 27 '12 22:01

Bruce


People also ask

How do you find all combinations of a list excel?

Joining queries to find all combinations of two lists Once the queries from the tables are ready, go to Data > Get Data > Combine Queries > Merge to open the Merge dialog of Power Query. Select each table in the drop downs. Click on the column for each table to select them.

How do you generate all possible combinations of multiple lists?

Add a Custom Column to and name it List1. Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!


2 Answers

You can do this easily using itertools.permutations():

>>> from itertools import permutations
>>> list(permutations([2, 3, 4]))
[(2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 2, 3), (4, 3, 2)]

And if for some reason you need lists instead of tuples:

>>> map(list, permutations([2, 3, 4]))
[[2, 3, 4], [2, 4, 3], [3, 2, 4], [3, 4, 2], [4, 2, 3], [4, 3, 2]]
like image 50
Andrew Clark Avatar answered Oct 05 '22 00:10

Andrew Clark


You are looking for permutations, something like this should work:

import itertools
itertools.permutations([2,3,4])
like image 38
Soufiane Hassou Avatar answered Oct 05 '22 01:10

Soufiane Hassou