3
$\begingroup$

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!!!

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

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}}} *)
$\endgroup$
3
$\begingroup$

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}}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.