RazgrizHsu
How to add key/value element to List with variable
we can create a list like this
list = [ a: 1, b: 2, c: 3 ]
but i can’t found api to add element with key to list?
list = []
key = :a
value = 1
#wrong ( * (SyntaxError) iex:4: syntax error before: '=>' )
list = list ++ [ key => value ]
anyone know how to do that?
thank you 
Marked As Solved
LostKobrakai
Keyword lists are syntax sugar over a list of tuples, which are strictly {atom(), term()}. So you can do list ++ [{key, value}].
Also Liked
lpil
As an extra tip, list ++ [{key, value}] is quite slow as you need to traverse the entire list to add [{key, value}] to the end.
As a rule of thumb you should add elements to the front of the list, which happens in constant time [{key, value} | list]
NobbZ
Besides from what have been said already, you also can use Keyword.put/3.
hauleth
Which is slower than [{key, value} | list] as this need to traverse all list and remove duplicates.
NobbZ
Yes, it is, but on the other hand side guarantees that the key is available only once and also that the kw list is a valid kw list.
Speed is not always everything.







