I have a list:
a = [1,2,4,5,6,7,8,9,9,88,88]
In Python, it's simple to get last n items:
a[-n:]
Whats equivalent in Elixir?
The last() function of the List module returns the last item in the list or nil. int length = sizeof(items) / sizeof(items[0]); int x = items[length - 1];
You can either do [head | tail]. = list (If you need the first element, head, as well) or tail = tl(list) (if you don't need the head) to get the tail of a list, then just map over that.
The length() function returns the length of the list that is passed as a parameter.
Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.
Use Enum.take/2
with a negative value:
iex(1)> list = [1, 2, 4, 5, 6, 7, 8, 9, 9, 88, 88] iex(2)> Enum.take(list, -4) |> IO.inspect(charlists: :as_lists) [9, 9, 88, 88]
take(enumerable, count)
[...]
count
must be an integer. If a negativecount
is given, the lastcount
values will be taken. [...]
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