Add new element to list

zero_coding picture zero_coding · Feb 20, 2016 · Viewed 60.6k times · Source

I was trying to add a new element into a list as follow:

iex(8)> l = [3,5,7,7,8] ++ 3
[3, 5, 7, 7, 8 | 3]
iex(9)> l
[3, 5, 7, 7, 8 | 3]

Why did I get on the 5th position like

8 | 3

What it does mean?
And how can I add new element to the list?

--------Update--------
I try to loop the list as follow:

iex(2)> l = [1,2] ++ 3
[1, 2 | 3]
iex(3)> Enum.each(l, fn(x) -> IO.puts(x) end)
1
2
** (FunctionClauseError) no function clause matching in Enum."-each/2-lists^foreach/1-0-"/2
    (elixir) lib/enum.ex:604: Enum."-each/2-lists^foreach/1-0-"(#Function<6.54118792/1 in :erl_eval.expr/5>, 3)
    (elixir) lib/enum.ex:604: Enum.each/2

Since the pointer of the number 2 is not pointing to a list, rather to value 3, how can I loop the list?

Answer

Chilian picture Chilian · May 9, 2017

Just follow the Elixir docs to add an element to a list ( and keep performance in mind =) ):

iex> list = [1, 2, 3]
iex> [0 | list]   # fast
[0, 1, 2, 3]
iex> list ++ [4]  # slow
[1, 2, 3, 4]

https://hexdocs.pm/elixir/List.html