As:: : 'a -> 'a list -> 'a list
is used to add an element to the begin of a list, Could anyone tell me if there is a function to add an element to the end of a list? If not, I guess List.rev (element::(List.rev list))
is the most straightforward way to do it?
Thank you!
If we want to add an element at the end of a list, we should use append . It is faster and direct. If we want to add an element somewhere within a list, we should use insert . It is the only option for this.
Adding a string to a list inserts the string as a single element, and the element will be added to the list at the end. The list. append() will append it to the end of the list. You can refer to the below screenshot to see the output for add string to list python.
The reason there's not a standard function to do this is that appending at the end of a list is an anti-pattern (aka a "snoc list" or a Schlemiel the Painter algorithm). Adding an element at the end of a list requires a full copy of the list. Adding an element at the front of the list requires allocating a single cell—the tail of the new list can just point to the old list.
That said, the most straightforward way to do it is
let append_item lst a = lst @ [a]
list@[element]
should work. @
joins lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With