Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

elixir

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?

like image 228
Farshid Ashouri Avatar asked Jul 20 '16 17:07

Farshid Ashouri


People also ask

How do I get the last element in a list 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];

How do you access elements from a list in Elixir?

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.

How do you find the length of a list in Elixir?

The length() function returns the length of the list that is passed as a parameter.

Is Elixir a list?

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.


1 Answers

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. [...]

like image 138
Dogbert Avatar answered Oct 24 '22 23:10

Dogbert