Alex Antonov
Alex Antonov

Reputation: 15146

elixir - how to get all elements except last in the list?

Let say I have a list [1, 2, 3, 4]

How can I get all elements from this list except last? So, I'll have [1, 2, 3]

Upvotes: 25

Views: 7647

Answers (6)

Roman Rabinovich
Roman Rabinovich

Reputation: 918

Erlang

List = [1,2,3,4,5],
NewList = DropLast(List).

DropLast(List) while length(List) > 0 and is_list(List) ->
    {NewList, _} = lists:split(OldList, length(OldList)-1),
    NewList.

Upvotes: 0

Graham Conzett
Graham Conzett

Reputation: 8454

If you're looking to get both the last item and the rest of the list preceding it you can now use List.pop_at/3:

{last, rest} = List.pop_at([1, 2, 3], -1)
{3, [1, 2]}

https://hexdocs.pm/elixir/List.html#pop_at/3

Upvotes: 6

Nehal Hasnayeen
Nehal Hasnayeen

Reputation: 1223

Another option, though not elegant, would be -

list = [1, 2, 3, 4]
Enum.take(list, Enum.count(list) -1 )   # [1, 2, 3]

Upvotes: 0

Martijn
Martijn

Reputation: 1719

Another option besides the list |> Enum.reverse |> tl |> Enum.reverse mentioned before is Erlang's :lists.droplast function which is slower according to the documentation but creates less garbage because it doesn't create two new lists. Depending on your use case that might be an interesting one to use.

Upvotes: 2

Chris Schreiner
Chris Schreiner

Reputation: 854

Use Enum.drop/2 like this:

list = [1, 2, 3, 4]
Enum.drop list, -1      # [1, 2, 3]

Upvotes: 40

Alex Antonov
Alex Antonov

Reputation: 15146

My solution (I think it's not a clean, but it works!)

a = [1, 2, 3, 4]
[head | tail] = Enum.reverse(a)
Enum.reverse(tail) # [1, 2, 3]

Upvotes: 21

Related Questions