How would you simply remove 20 from the end of this example?
[46, 238, 64, 30, 105, 136, 98, 75, 23, 157, 11, 20]
Thanks to the Enum module, in Elixir we can trivially remove duplicates from a list. In the following example, we take a list of integers and pass it to the Enum. uniq/1 function which removes duplicates from the list without altering the original order of the remaining elements.
Using del The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1. The use of the negative index allows us to delete the last element, even without calculating the length of the list.
The easiest way to write it is actually Enum. drop(list, -1) .
The head is the first element of a list and the tail is the remainder of a list. They can be retrieved with the functions hd and tl. Let us assign a list to a variable and retrieve its head and tail.
fastest solution that I know of with @mudasobwa's one
solution 1:
x |> Enum.reverse() |> tl() |> Enum.reverse()
Some other solutions:
solution 2:
[k] = Enum.chunk(x, length(x)-1)
solution 3:
List.delete_at(x, length(x)-1)
solution 4:
x |> List.to_tuple() |> Tuple.delete_at(length(x)-1) |> Tuple.to_list
An even more interesting question, is how to do that the fastest way ? let's benchmark it !
I got the following result using Benchee, each solution was computed 50000 times, and I used a list created with Enum.to_list(1..10_000)
Name ips average deviation median 99th %
mudasobwa's solution 14.80 K 67.57 μs ±34.17% 79 μs 91 μs
solution 1 14.79 K 67.59 μs ±33.96% 79 μs 91 μs
solution 4 10.71 K 93.38 μs ±32.67% 81 μs 201 μs
Roman Rabinovich's solution 8.45 K 118.33 μs ±18.27% 118 μs 171 μs
OneSneakyMofo's solution 5.07 K 197.34 μs ±13.60% 193 μs 331 μs
dawner's solution 4.57 K 219.00 μs ±11.87% 216 μs 256.23 μs
solution 3 3.41 K 292.91 μs ±20.01% 290 μs 506.64 μs
solution 2 0.83 K 1205.52 μs ±22.25% 1105 μs 2061.77 μs
Comparison:
mudasobwa's solution 14.80 K
solution 1 14.79 K - 1.00x slower
solution 4 10.71 K - 1.38x slower
Roman Rabinovich's solution 8.45 K - 1.75x slower
OneSneakyMofo's solution 5.07 K - 2.92x slower
dawner's solution 4.57 K - 3.24x slower
solution 3 3.41 K - 4.33x slower
solution 2 0.83 K - 17.84x slower
You could do:
List.pop_at(x, -1)
{20, [46, 238, 64, 30, 105, 136, 98, 75, 23, 157, 11]}
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