Applying function to all elements of the list of list

Let's say we have a following list:

{{{1}, {3}, {5}, {1, 2}, {1, 2, 3, 4, 5}}, {{1}, {3}, {5}, {3, 4}, {1,2, 3, 4, 5}}, {{1}, {3}, {5}, {1, 2, 3}, {1, 2, 3, 4,5}}, {{1}, {3}, {5}, {3, 4, 5}, {1, 2, 3, 4,5}}, {{1}, {3}, {5}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}}}.

Now, I've written this simple function:

TransformToPoints[{a_}] :=
If[First[a] == 1,
{First[a] = 0, Last[a] = Last[a] + 1},
{First[a] = First[a] - 1, Last[a] = Last[a] + 1}]


so basically that function takes in a list and transforms it to the list of 2 elements, where those 2 elements are produced as described in the function. Now, I'd like to apply this function to all the elements of lists inside the big list above (which is usually much, much bigger) so the new list would look as follows:

{{{0,2},{2,4},{4,6},{0,3},{0,6}},{{0,2},{2,4},{4,6},{2,5},{0,6}},...,{{0,2},{2,4},{4,6},{0,5},{0,6}}}

What would be the quickest way to do that?

An alternative way to define your transformation function:

tToP[lst_List] := #[[{1, -1}]] + {-1, 1} & /@ lst;

list = {{{1}, {3}, {5}, {1, 2}, {1, 2, 3, 4, 5}},
{{1}, {3}, {5}, {3, 4}, {1,2, 3, 4, 5}},
{{1}, {3}, {5}, {1, 2, 3}, {1, 2, 3, 4,5}},
{{1}, {3}, {5}, {3, 4, 5}, {1, 2, 3, 4,5}},
{{1}, {3}, {5}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}}};

tToP /@ list


{{{0, 2}, {2, 4}, {4, 6}, {0, 3}, {0, 6}},
{{0, 2}, {2, 4}, {4, 6}, {2, 5}, {0, 6}},
{{0, 2}, {2, 4}, {4, 6}, {0, 4}, {0, 6}},
{{0, 2}, {2, 4}, {4, 6}, {2, 6}, {0, 6}},
{{0, 2}, {2, 4}, {4, 6}, {0, 5}, {0, 6}}}

Alternatively, you can use Map[tToP, list, 1].

• Thank you @kglr, I really like it ! I'll accept your answer since it uses this unintuitive (at least to me) approach. Jan 14, 2019 at 21:23
• @amator2357, thank you for the accept.
– kglr
Jan 14, 2019 at 21:33

First of all, you can't do assignment to variables that you entered into the function in this case. It's not necessary either, just define your function as follows (notice that I also fixed your matching pattern):

Clear[TransformToPoints]
TransformToPoints[a_List] := If[First[a] == 1, {0, Last[a] + 1}, {First[a] - 1, Last[a] + 1}]


To apply the function to all elements of the big list, just use Map. However, you don't want to map onto the first level but the second level down, so this is what you do:

Map[
TransformToPoints,
{
{{1}, {3}, {5}, {1, 2}, {1, 2, 3, 4, 5}}, {{1}, {3}, {5}, {3, 4}, {1, 2, 3, 4, 5}},
{{1}, {3}, {5}, {1, 2, 3}, {1, 2, 3, 4, 5}}, {{1}, {3}, {5}, {3, 4, 5}, {1, 2, 3, 4, 5}}, {{1}, {3}, {5}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}}
},
{2} (* map onto the 2nd level*)
]


{{{0, 2}, {2, 4}, {4, 6}, {0, 3}, {0, 6}}, {{0, 2}, {2, 4}, {4, 6}, {2, 5}, {0, 6}}, {{0, 2}, {2, 4}, {4, 6}, {0, 4}, {0, 6}}, {{0, 2}, {2, 4}, {4, 6}, {2, 6}, {0, 6}}, {{0, 2}, {2, 4}, {4, 6}, {0, 5}, {0, 6}}}

• Thank you so much! Jan 14, 2019 at 17:44