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 :slight_smile:

Keyword lists are syntax sugar over a list of tuples, which are strictly {atom(), term()}. So you can do list ++ [{key, value}].


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]


Besides from what have been said already, you also can use Keyword.put/3.


Which is slower than [{key, value} | list] as this need to traverse all list and remove duplicates.

1 Like

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.

1 Like

thank you very much guys, it’s great answer and performance advise