Data Structures
Elixir Keyword Lists
Using Keyword Lists
Elixir keyword lists are lists of key-value tuples for options.
What are Elixir Keyword Lists?
Elixir keyword lists are a collection of key-value tuples, similar to maps, but with some important distinctions. These lists are commonly used for passing options to functions because they maintain the order of elements and allow duplicate keys.
Creating Keyword Lists
Creating a keyword list in Elixir is straightforward. You simply define a list of tuples where the first element is the key (an atom) and the second is the value.
Accessing Keyword List Elements
To access elements in a keyword list, you can use the built-in functions Keyword.get/3
or pattern matching. Let's see how they work.
Updating Keyword Lists
Updating a keyword list can be done using the Keyword.put/3
function, which adds a key-value pair to the list. If the key already exists, it will be replaced.
Advantages of Keyword Lists
Keyword lists are particularly useful when you need to maintain the order of options or allow for duplicate keys, which is not possible with maps. They are commonly used in function arguments to provide options.
Limitations of Keyword Lists
While keyword lists are flexible, they are not as performant as maps for large datasets due to their linear search time complexity. Therefore, it's best to use them for small collections of options.