Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new element to list

Tags:

elixir

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?

like image 564
softshipper Avatar asked Feb 20 '16 20:02

softshipper


People also ask

How do you add an element in the middle of a list in Python?

insert() Method. Use the insert() method when you want to add data to the beginning or middle of a list. Take note that the index to add the new element is the first parameter of the method.


2 Answers

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

like image 113
Chilian Avatar answered Oct 01 '22 22:10

Chilian


The ++ operator is for concatenating two lists, then maybe what you want to do in order to add a new element is to put it within a list. Then, I think you should add the 3 into another list:

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

[3, 5, 7, 7, 8, 3]

like image 37
Salvador Medina Avatar answered Oct 01 '22 22:10

Salvador Medina