How to generate a list from permutations of other lists in Mathematica

I ran into a pretty simple problem: I need to build a list with all permutations of values ​​from two different lists in Mathematica. Say a={1,2} and b={4,5} I need a result

 c={{1,4},{1,5},{2,4},{2,5}} 

Can someone please give me an idea on how to achieve this? Thank you very much,

Philipp

+4
source share
2 answers

Here is one way

 In[2]:= Tuples[{{1, 2}, {4, 5}}] Out[2]= {{1, 4}, {1, 5}, {2, 4}, {2, 5}} 
+4
source

The built-in Tuples function does exactly what you want:

 In[1]:= a = {1, 2}; b = {4, 5}; In[2]:= c = Tuples[{a, b}] Out[2]= {{1, 4}, {1, 5}, {2, 4}, {2, 5}} 

You can also accomplish this with Flatten and the more general Outer :

 In[3]:= Flatten[Outer[List, a, b], 1] Out[3]= {{1, 4}, {1, 5}, {2, 4}, {2, 5}} 

I mention this last fact, because a lot of the time when I find myself using Tuples , I do it as an intermediate step before Tuples Apply to each of the generated subscriptions right away and using Outer can save me.

+3
source

Source: https://habr.com/ru/post/1340803/


All Articles