Forum Discussion

Dicken's avatar
Dicken
Post Prodigy
18 hours ago

insert values in nested lists except last

I want to insert rows into a list / table , i have used lists here for clarity,   but not the last so 
 { { 1,2,3}, {1,2,3} , { 1,2,3} } =   { 1,2,3,"X"} , {1,2,3,"X"} , {1,2,3}} 

I have two methods which work, but would be interested in any other approaches, 

 let
    Source = { {1,2,3}, {4,5,6}, {7,8,9} , {10,11,12}},
     p =  List.Positions( List.RemoveLastN( Source,1)) ,
    addlists = List.Transform( p, (x)=>  Source {x} & {""} ) & List.LastN( Source ,1)
  in
    addlistslet

Or 
    Source = { {1,2,3}, {4,5,6}, {7,8,9} , {10,11,12}},
    transfrom = List.Transform( Source, (x)=>  List.InsertRange( x, List.Count(x), {""} )),    result = List.ReplaceRange( transfrom, List.Count( transfrom) -1, 1, List.LastN( Source,1) )
in
    result


I did try putting these in code quotes, but it did not seem to work, so sorry for that. 

Richard 




4 Replies

  • ShivekMaharaj's avatar
    ShivekMaharaj
    Impactful Individual

    Hi Dicken​,

    You can simplify your first approach by transforming everything except the last item directly, then appending the last item unchanged:

    let
        Source = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}},
        Result =
            List.Transform(
                List.RemoveLastN(Source, 1),
                each _ & {"X"}
            )
            & List.LastN(Source, 1)
    in
        Result

    This gives:

    {{1,2,3,"X"}, {4,5,6,"X"}, {7,8,9,"X"}, {10,11,12}}

    List.RemoveLastN removes the final nested list, List.Transform appends "X" to everything remaining, and List.LastN adds the untouched final item back.

    It avoids needing the positions or a subsequent List.ReplaceRange.

    • slorin's avatar
      slorin
      Super User

      Hi, 

      = List.Transform(
           List.Zip({
               alist,
               List.Repeat({{"X"}}, List.Count(alist)-1) & {{}} }),
           List.Combine)

       

      Stéphane

      • slorin's avatar
        slorin
        Super User

        To avoid adding a "null" to the last item

        = List.Transform(
              List.Zip({
                  List.RemoveLastN(Source, 1),
                  List.Repeat({{"X"}}, List.Count(Source)-1)}),
              List.Combine)
        & {List.Last(Source)}

  • let     Source = { {1,2,3}, {4,5,6}, {7,8,9} , {10,11,12}},     p =  List.Count(Source) - 1,     addlists = List.Generate(       ()=> 0,        each _ <= p,        each _ + 1,        each if _ = p then Source{p} else Source{p} & {"X"}     )   in     addlists