Elixir: How to get last n items in a list?

Farsheed picture Farsheed · Jul 20, 2016 · Viewed 11.5k times · Source

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?

Answer

Dogbert picture Dogbert · Jul 20, 2016

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 negative count is given, the last count values will be taken. [...]