Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an Elixir list, how to get the middle value?

Tags:

elixir

I need get a middle value from the list.

How to do it using list[0] or list[3..-1] in elixir?

e.g:

 list = [1,2,3,4,5,6]
 list[0] [1]
 list[2..-1] [3,4,5,6]

And how to do it using Tuple?

like image 493
Yingce Avatar asked Nov 30 '25 05:11

Yingce


2 Answers

Using Enum.slice/2 you could do :

Enum.slice(list, 2..-1) # [3, 4, 5, 6]

And Enum.take/2 :

Enum.take(list, 1) # [1]
like image 69
Kernael Avatar answered Dec 02 '25 04:12

Kernael


To get the exact middle value (as suggested by the heading of the question), you can do the following:

# Given a list: li
midPos = (length(li) -1) |> div 2
Enum.at li, midPos  


# Or in one line 
Enum.at(li,(length(li) -1) |> div 2)
like image 40
coderVishal Avatar answered Dec 02 '25 03:12

coderVishal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!