Appending to a List

As we saw, prepending to a LW list is very easy. We just have to wrap a list with the new element. For example, if we want to prepend element P to a list L, then the new list is:

[P, L]

But appending an element to the end of the list requires more steps. This is because of LW list's structure. Let's consider an example. Suppose that we want to append 3 to the following list:

[1, [2, [ ] ] ]

The result should be

[1, [2, [3, [ ] ] ] ]

It is quite intuitive, but unlike prepending, we do not know of a property that can describe this in one step. But we do know we can describe it with a few different properties.

What we do is we first reverse the list, prepend the new element, and then reverse the list again.

For example suppose that we have a list L:

[1, [2, [3, []]]]

And we want to append 4 to it:

[1, [2, [3, [4, []]]]]

We first reverse the list:

[3, [2, [1, []]]]

Then we prepend the new element:

[4, [3, [2, [1, []]]]]

Finally, reverse the previous list:

[1, [2, [3, [4, []]]]]

Quiz (1 point)

What is the result if we append 7 to the following list?

[3, [6, [ ] ] ]

Become a subscriber to save your progress, see the correct answer, and more!

Comments

Please log in to add comments