 # `ListAppend` formula for Nested Lists

Not possible to create nested lists with ListCombine because it removes all nested lists.

I would like to be able to take an existing nested list, e.g.

``````List(
List("A", 1),
List("B", 2)
)
``````

``````List("C", 3)
``````

To the end to end up with: Not currently possible with `ListCombine` as

``````List(
List("A", 1),
List("B", 2)
).ListCombine(List("C", 3))
``````

Returns: `ListCombine` might better be called `ListMerge` or `ListFlatten` due to this behavior.

Ok, there is a way to do this. It’s super hacky but I guess the community could benefit from it since I didn’t see any posts on how to make nested lists.

Let’s say you have an existing formula called `MyList` that looks like this:

You can append `List("C", 3)` to that list with the formula:

``````Sequence(1, MyList.Count() + 1).FormulaMap(
If(CurrentValue <= MyList.Count(),
List(
MyList.Nth(CurrentValue).Nth(1),
MyList.Nth(CurrentValue).Nth(2)
),
List("C", 3)
)
)
``````

Just to show it works: Of course all of this could be solved much more elegantly with syntax like:

``````MyList.ListAppend(List("C", 3))
``````
1 Like

@cnr there’s a `Splice()` formula specifically for list modification, i.e. inserting or deleting items:

``````List(
List("A", "B"),
List("C", "D")
).Splice(3, 0, List(List("E", "F")))
``````

means at position 3 delete zero items and insert a `List("E", "F")` and return `[A, B], [C, D], [E, F]`: Please note the `List(List(...))` — if you just submitted a non-nested list to the Splice formula it would insert list items one by one and would get `[A, B], [C, D], E, F`. The Splice function unwraps one list but doesn’t unwrap the second.

5 Likes

I didn’t know this worked! Not exactly intuitive, but useful to know. Thank you.

I suppose the most general way to implement `Append` using `Splice` would be:

``````WithName(
List(
List("A", "B"),
List("C", "D")
), TargetList,
TargetList.Splice(TargetList.Count(), 0, List(List("E", "F"))
)
``````

So that the TargetList can be of any length.

1 Like