Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

permutations of two lists in python

Tags:

python

I have two lists like:

list1 = ['square','circle','triangle'] list2 = ['red','green'] 

How can I create all permutations of these lists, like this:

[   'squarered', 'squaregreen',   'redsquare', 'greensquare',   'circlered', 'circlegreen',   'redcircle', 'greencircle',   'trianglered', 'trianglegreen',   'redtriangle', 'greentriangle' ] 

Can I use itertools for this?

like image 600
Edward Avatar asked Dec 23 '09 14:12

Edward


People also ask

How do you get all the combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

How do you generate all possible combinations of two lists?

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!

Is there a permutation function in Python?

perm() function in Python is used to return the number of permutations of k items from a group of n items, i.e., it helps us figure out the number of ways in which we can choose k items from n items with order and without repetition.


1 Answers

You want the itertools.product method, which will give you the Cartesian product of both lists.

>>> import itertools >>> a = ['foo', 'bar', 'baz'] >>> b = ['x', 'y', 'z', 'w']  >>> for r in itertools.product(a, b): print r[0] + r[1] foox fooy fooz foow barx bary barz barw bazx bazy bazz bazw 

Your example asks for the bidirectional product (that is, you want 'xfoo' as well as 'foox'). To get that, just do another product and chain the results:

>>> for r in itertools.chain(itertools.product(a, b), itertools.product(b, a)): ...   print r[0] + r[1] 
like image 175
John Feminella Avatar answered Sep 28 '22 07:09

John Feminella