# Problem with Inserting in a Nested list

So I have a nested list like this:

{{{0}},{{0}},{{0}}}


Now i need to Insert in the first sublist like this

list = Insert[list,1,{1,1,1}]
list = Insert[list,1,{1,1,2}]
{{{1,1,0}},{{0}},{{0}}}


This works, but i know want to Insert a 2 in the first sublist to get this result:

{{{1,1,0},{2,2}},{{0}},{{0}}}


But Inserting wont work:

list = Insert[list,3,{1,2,1}]
Insert::ins: Cannot insert at position {1,2,1} in {{{1,1}},{{0}},{{0}}}


So what i have to do is use PadRight to make the list bigger, but it extends the list in every sublist meaning it would be like this:

{{{1,1,0},{0}},{{0},{0}},{{0},{0}}}


With 2 numbers this wouldnt be a Problem but in a single sublist there might be 10000 to 20000 numbers wich i think greatly increases the runtime and runtime is Pretty important. If anyone knows how to Insert in a nested list without having to expand it with PadRight then an Answer would be much appreciated. Thanks in Ad,vance!!!

• a typo? ( your first code block should give {{{1, 1, 0}}, {{0}}, {{0}}})
– kglr
Oct 25, 2019 at 8:03
• Yes that is correct il Change that Oct 25, 2019 at 8:04

The problem is that {1, 2} does not exist, so you can insert something into it (hence the error message). To work around this, you can insert an empty list ({}) first:

list = {{{}}, {{0}}, {{0}}};
list = Insert[list, 1, {1, 1, 1}];
list = Insert[list, 1, {1, 1, 2}]
(* {{{1, 1}}, {{0}}, {{0}}} *)

(* insert empty list *)
list = Insert[list, {}, {1, 2}]
(* {{{1, 1}, {}}, {{0}}, {{0}}}

(* insert into new empty list *)
Insert[list, 3, {1, 2, 1}] *)
(* {{{1, 1}, {3}}, {{0}}, {{0}}} *)


You can also insert {3} at {1, 2} directly:

list = {{{1, 1}}, {{0}}, {{0}}};

Insert[list, {3}, {1, 2}]
(* {{{1, 1}, {3}}, {{0}}, {{0}}} *)


You can use Fold to have a sequence of insertions in a single step:

list = {{{0}}, {{0}}, {{0}}};

Fold[Insert[#, #2[[1]], #2[[2]]] &,
list,
{{1, {1, 1, 1}},
{1, {1, 1, 1}},
{{2, 2}, {1, 2}}}]


{{{1, 1, 0}, {2, 2}}, {{0}}, {{0}}}

Alternatively, make 2 insertions (instead of 3):

Fold[Insert[#, #2[[1]], #2[[2]]] &,
list,
{{foo[1, 1], {1, 1, 1}},
{{2, 2}, {1, 2}}}] /. foo -> Sequence


{{{1, 1, 0}, {2, 2}}, {{0}}, {{0}}}