How to get list elements by index in elixir How to get list elements by index in elixir arrays arrays

How to get list elements by index in elixir


You can use pattern matching for that:

[from, to] = String.split line, " "

Maybe you want to add parts: 2 option to ensure you will get only two parts in case there is more than one space in the line:

[from, to] = String.split line, " ", parts: 2

There is also Enum.at/3, which would work fine here but is unidiomatic. The problem with Enum.at is that due to the list implementation in Elixir, it needs to traverse the entire list up to the requested index so it can be very inefficient for large lists.


Edit: here's the requested example with Enum.at, but I would not use it in this case

parts = String.split line, " "from = Enum.at(parts, 0)to = Enum.at(parts, 1)