On this page
List
Functions that work on (linked) lists.
Many of the functions provided for lists, which implement the Enumerable protocol, are found in the Enum module.
Additionally, the following functions and operators for lists are found in Kernel:
Lists in Elixir are specified between square brackets:
iex> [1, "two", 3, :four]
[1, "two", 3, :four]
Two lists can be concatenated and subtracted using the Kernel.++/2 and Kernel.--/2 operators:
iex> [1, 2, 3] ++ [4, 5, 6]
[1, 2, 3, 4, 5, 6]
iex> [1, true, 2, false, 3, true] -- [true, false]
[1, 2, 3, true]
Lists in Elixir are effectively linked lists, which means they are internally represented in pairs containing the head and the tail of a list:
iex> [head | tail] = [1, 2, 3]
iex> head
1
iex> tail
[2, 3]
Similarly, we could write the list [1, 2, 3] using only such pairs (called cons cells):
iex> [1 | [2 | [3 | []]]]
[1, 2, 3]
Some lists, called improper lists, do not have an empty list as the second element in the last cons cell:
iex> [1 | [2 | [3 | 4]]]
[1, 2, 3 | 4]
Although improper lists are generally avoided, they are used in some special circumstances like iodata and chardata entities (see the IO module).
Due to their cons cell based representation, prepending an element to a list is always fast (constant time), while appending becomes slower as the list grows in size (linear time):
iex> list = [1, 2, 3]
iex> [0 | list] # fast
[0, 1, 2, 3]
iex> list ++ [4] # slow
[1, 2, 3, 4]
Most of the functions in this module work in linear time. This means that, that the time it takes to perform an operation grows at the same rate as the length of the list. For example length/1 and last/1 will run in linear time because they need to iterate through every element of the list, but first/1 will run in constant time because it only needs the first element.
Charlists
If a list is made of non-negative integers, where each integer represents a Unicode code point, the list can also be called a charlist. These integers must:
- be within the range
0..0x10FFFF(0..1_114_111); - and be out of the range
0xD800..0xDFFF(55_296..57_343), which is reserved in Unicode for UTF-16 surrogate pairs.
Elixir uses single quotes to define charlists:
iex> 'héllo'
[104, 233, 108, 108, 111]
In particular, charlists will be printed back by default in single quotes if they contain only printable ASCII characters:
iex> 'abc'
'abc'
The rationale behind this behaviour is to better support Erlang libraries which may return text as charlists instead of Elixir strings. One example of such functions is Application.loaded_applications/0:
Application.loaded_applications()
#=> [
#=> {:stdlib, 'ERTS CXC 138 10', '2.6'},
#=> {:compiler, 'ERTS CXC 138 10', '6.0.1'},
#=> {:elixir, 'elixir', '1.0.0'},
#=> {:kernel, 'ERTS CXC 138 10', '4.1'},
#=> {:logger, 'logger', '1.0.0'}
#=> ]
A list can be checked if it is made of only printable ASCII characters with ascii_printable?/2.
Improper lists are never deemed as charlists.
Summary
Functions
- ascii_printable?(list, limit \\ :infinity)
-
Checks if
listis a charlist made only of printable ASCII characters. - delete(list, element)
-
Deletes the given
elementfrom thelist. Returns a new list without the element. - delete_at(list, index)
-
Produces a new list by removing the value at the specified
index. - duplicate(elem, n)
-
Duplicates the given element
ntimes in a list. - first(list)
-
Returns the first element in
listorniliflistis empty. - flatten(list)
-
Flattens the given
listof nested lists. - flatten(list, tail)
-
Flattens the given
listof nested lists. The listtailwill be added at the end of the flattened list. - foldl(list, acc, fun)
-
Folds (reduces) the given list from the left with a function. Requires an accumulator.
- foldr(list, acc, fun)
-
Folds (reduces) the given list from the right with a function. Requires an accumulator.
- improper?(list)
-
Returns
trueiflistis an improper list. Otherwise returnsfalse. - insert_at(list, index, value)
-
Returns a list with
valueinserted at the specifiedindex. - keydelete(list, key, position)
-
Receives a
listof tuples and deletes the first tuple where the element atpositionmatches the givenkey. Returns the new list. - keyfind(list, key, position, default \\ nil)
-
Receives a list of tuples and returns the first tuple where the element at
positionin the tuple matches the givenkey. - keymember?(list, key, position)
-
Receives a list of tuples and returns
trueif there is a tuple where the element atpositionin the tuple matches the givenkey. - keyreplace(list, key, position, new_tuple)
-
Receives a list of tuples and if the identified element by
keyatpositionexists, it is replaced withnew_tuple. - keysort(list, position)
-
Receives a list of tuples and sorts the elements at
positionof the tuples. The sort is stable. - keystore(list, key, position, new_tuple)
-
Receives a
listof tuples and replaces the element identified bykeyatpositionwithnew_tuple. - keytake(list, key, position)
-
Receives a
listof tuples and returns the first tuple where the element atpositionin the tuple matches the givenkey, as well as thelistwithout found tuple. - last(list)
-
Returns the last element in
listorniliflistis empty. - myers_difference(list1, list2)
-
Returns a keyword list that represents an edit script.
- myers_difference(list1, list2, diff_script)
-
Returns a keyword list that represents an edit script with nested diffs.
- pop_at(list, index, default \\ nil)
-
Returns and removes the value at the specified
indexin thelist. - replace_at(list, index, value)
-
Returns a list with a replaced value at the specified
index. - starts_with?(list, prefix)
-
Returns
trueifliststarts with the givenprefixlist; otherwise returnsfalse. - to_atom(charlist)
-
Converts a charlist to an atom.
- to_charlist(list)
-
Converts a list of integers representing code points, lists or strings into a charlist.
- to_existing_atom(charlist)
-
Converts a charlist to an existing atom. Raises an
ArgumentErrorif the atom does not exist. - to_float(charlist)
-
Returns the float whose text representation is
charlist. - to_integer(charlist)
-
Returns an integer whose text representation is
charlist. - to_integer(charlist, base)
-
Returns an integer whose text representation is
charlistin basebase. - to_string(list)
-
Converts a list of integers representing code points, lists or strings into a string.
- to_tuple(list)
-
Converts a list to a tuple.
- update_at(list, index, fun)
-
Returns a list with an updated value at the specified
index. - wrap(term)
-
Wraps
termin a list if this is not list. - zip(list_of_lists)
-
Zips corresponding elements from each list in
list_of_lists.
Functions
ascii_printable?(list, limit \\ :infinity)
Specs
ascii_printable?(list(), 0) :: true
ascii_printable?([], limit) :: true when limit: :infinity | pos_integer()
ascii_printable?([...], limit) :: boolean()
when limit: :infinity | pos_integer()
Checks if list is a charlist made only of printable ASCII characters.
Takes an optional limit as a second argument. ascii_printable?/2 only checks the printability of the list up to the limit.
A printable charlist in Elixir contains only the printable characters in the standard seven-bit ASCII character encoding, which are characters ranging from 32 to 126 in decimal notation, plus the following control characters:
?\a- Bell?\b- Backspace?\t- Horizontal tab?\n- Line feed?\v- Vertical tab?\f- Form feed?\r- Carriage return?\e- Escape
For more information read the Character groups section in the Wikipedia article of the ASCII standard.
Examples
iex> List.ascii_printable?('abc')
true
iex> List.ascii_printable?('abc' ++ [0])
false
iex> List.ascii_printable?('abc' ++ [0], 2)
true
Improper lists are not printable, even if made only of ASCII characters:
iex> List.ascii_printable?('abc' ++ ?d)
false
delete(list, element)
Specs
delete([], any()) :: []
delete([...], any()) :: list()
Deletes the given element from the list. Returns a new list without the element.
If the element occurs more than once in the list, just the first occurrence is removed.
Examples
iex> List.delete([:a, :b, :c], :a)
[:b, :c]
iex> List.delete([:a, :b, :c], :d)
[:a, :b, :c]
iex> List.delete([:a, :b, :b, :c], :b)
[:a, :b, :c]
iex> List.delete([], :b)
[]
delete_at(list, index)
Specs
delete_at(list(), integer()) :: list()
Produces a new list by removing the value at the specified index.
Negative indices indicate an offset from the end of the list. If index is out of bounds, the original list is returned.
Examples
iex> List.delete_at([1, 2, 3], 0)
[2, 3]
iex> List.delete_at([1, 2, 3], 10)
[1, 2, 3]
iex> List.delete_at([1, 2, 3], -1)
[1, 2]
duplicate(elem, n)
Specs
duplicate(any(), 0) :: []
duplicate(elem, pos_integer()) :: [elem, ...] when elem: var
Duplicates the given element n times in a list.
n is an integer greater than or equal to 0.
If n is 0, an empty list is returned.
Examples
iex> List.duplicate("hello", 0)
[]
iex> List.duplicate("hi", 1)
["hi"]
iex> List.duplicate("bye", 2)
["bye", "bye"]
iex> List.duplicate([1, 2], 3)
[[1, 2], [1, 2], [1, 2]]
first(list)
Specs
first([]) :: nil
first([elem, ...]) :: elem when elem: var
Returns the first element in list or nil if list is empty.
Examples
iex> List.first([])
nil
iex> List.first([1])
1
iex> List.first([1, 2, 3])
1
flatten(list)
Specs
flatten(deep_list) :: list() when deep_list: [any() | deep_list]
Flattens the given list of nested lists.
Empty list elements are discarded.
Examples
iex> List.flatten([1, [[2], 3]])
[1, 2, 3]
iex> List.flatten([[], [[], []]])
[]
flatten(list, tail)
Specs
flatten(deep_list, [elem]) :: [elem]
when deep_list: [elem | deep_list], elem: var
Flattens the given list of nested lists. The list tail will be added at the end of the flattened list.
Empty list elements from list are discarded, but not the ones from tail.
Examples
iex> List.flatten([1, [[2], 3]], [4, 5])
[1, 2, 3, 4, 5]
iex> List.flatten([1, [], 2], [3, [], 4])
[1, 2, 3, [], 4]
foldl(list, acc, fun)
Specs
foldl([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
Folds (reduces) the given list from the left with a function. Requires an accumulator.
Examples
iex> List.foldl([5, 5], 10, fn x, acc -> x + acc end)
20
iex> List.foldl([1, 2, 3, 4], 0, fn x, acc -> x - acc end)
2
foldr(list, acc, fun)
Specs
foldr([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
Folds (reduces) the given list from the right with a function. Requires an accumulator.
Examples
iex> List.foldr([1, 2, 3, 4], 0, fn x, acc -> x - acc end)
-2
improper?(list)
Specs
improper?(maybe_improper_list()) :: boolean()
Returns true if list is an improper list. Otherwise returns false.
Examples
iex> List.improper?([1, 2 | 3])
true
iex> List.improper?([1, 2, 3])
false
insert_at(list, index, value)
Specs
insert_at(list(), integer(), any()) :: list()
Returns a list with value inserted at the specified index.
Note that index is capped at the list length. Negative indices indicate an offset from the end of the list.
Examples
iex> List.insert_at([1, 2, 3, 4], 2, 0)
[1, 2, 0, 3, 4]
iex> List.insert_at([1, 2, 3], 10, 0)
[1, 2, 3, 0]
iex> List.insert_at([1, 2, 3], -1, 0)
[1, 2, 3, 0]
iex> List.insert_at([1, 2, 3], -10, 0)
[0, 1, 2, 3]
keydelete(list, key, position)
Specs
keydelete([tuple()], any(), non_neg_integer()) :: [tuple()]
Receives a list of tuples and deletes the first tuple where the element at position matches the given key. Returns the new list.
Examples
iex> List.keydelete([a: 1, b: 2], :a, 0)
[b: 2]
iex> List.keydelete([a: 1, b: 2], 2, 1)
[a: 1]
iex> List.keydelete([a: 1, b: 2], :c, 0)
[a: 1, b: 2]
keyfind(list, key, position, default \\ nil)
Specs
keyfind([tuple()], any(), non_neg_integer(), any()) :: any()
Receives a list of tuples and returns the first tuple where the element at position in the tuple matches the given key.
If no matching tuple is found, default is returned.
Examples
iex> List.keyfind([a: 1, b: 2], :a, 0)
{:a, 1}
iex> List.keyfind([a: 1, b: 2], 2, 1)
{:b, 2}
iex> List.keyfind([a: 1, b: 2], :c, 0)
nil
keymember?(list, key, position)
Specs
keymember?([tuple()], any(), non_neg_integer()) :: boolean()
Receives a list of tuples and returns true if there is a tuple where the element at position in the tuple matches the given key.
Examples
iex> List.keymember?([a: 1, b: 2], :a, 0)
true
iex> List.keymember?([a: 1, b: 2], 2, 1)
true
iex> List.keymember?([a: 1, b: 2], :c, 0)
false
keyreplace(list, key, position, new_tuple)
Specs
keyreplace([tuple()], any(), non_neg_integer(), tuple()) :: [tuple()]
Receives a list of tuples and if the identified element by key at position exists, it is replaced with new_tuple.
Examples
iex> List.keyreplace([a: 1, b: 2], :a, 0, {:a, 3})
[a: 3, b: 2]
iex> List.keyreplace([a: 1, b: 2], :a, 1, {:a, 3})
[a: 1, b: 2]
keysort(list, position)
Specs
keysort([tuple()], non_neg_integer()) :: [tuple()]
Receives a list of tuples and sorts the elements at position of the tuples. The sort is stable.
Examples
iex> List.keysort([a: 5, b: 1, c: 3], 1)
[b: 1, c: 3, a: 5]
iex> List.keysort([a: 5, c: 1, b: 3], 0)
[a: 5, b: 3, c: 1]
keystore(list, key, position, new_tuple)
Specs
keystore([tuple()], any(), non_neg_integer(), tuple()) :: [tuple(), ...]
Receives a list of tuples and replaces the element identified by key at position with new_tuple.
If the element does not exist, it is added to the end of the list.
Examples
iex> List.keystore([a: 1, b: 2], :a, 0, {:a, 3})
[a: 3, b: 2]
iex> List.keystore([a: 1, b: 2], :c, 0, {:c, 3})
[a: 1, b: 2, c: 3]
keytake(list, key, position)
Specs
keytake([tuple()], any(), non_neg_integer()) :: {tuple(), [tuple()]} | nil
Receives a list of tuples and returns the first tuple where the element at position in the tuple matches the given key, as well as the list without found tuple.
If such a tuple is not found, nil will be returned.
Examples
iex> List.keytake([a: 1, b: 2], :a, 0)
{{:a, 1}, [b: 2]}
iex> List.keytake([a: 1, b: 2], 2, 1)
{{:b, 2}, [a: 1]}
iex> List.keytake([a: 1, b: 2], :c, 0)
nil
last(list)
Specs
last([]) :: nil
last([elem, ...]) :: elem when elem: var
Returns the last element in list or nil if list is empty.
Examples
iex> List.last([])
nil
iex> List.last([1])
1
iex> List.last([1, 2, 3])
3
myers_difference(list1, list2)
Specs
myers_difference(list(), list()) :: [{:eq | :ins | :del, list()}]
Returns a keyword list that represents an edit script.
The algorithm is outlined in the "An O(ND) Difference Algorithm and Its Variations" paper by E. Myers.
An edit script is a keyword list. Each key describes the "editing action" to take in order to bring list1 closer to being equal to list2; a key can be :eq, :ins, or :del. Each value is a sublist of either list1 or list2 that should be inserted (if the corresponding key :ins), deleted (if the corresponding key is :del), or left alone (if the corresponding key is :eq) in list1 in order to be closer to list2.
See myers_difference/3 if you want to handle nesting in the diff scripts.
Examples
iex> List.myers_difference([1, 4, 2, 3], [1, 2, 3, 4])
[eq: [1], del: [4], eq: [2, 3], ins: [4]]
myers_difference(list1, list2, diff_script)
Specs
myers_difference(list(), list(), (term(), term() -> script | nil)) :: script
when script: [{:eq | :ins | :del | :diff, list()}]
Returns a keyword list that represents an edit script with nested diffs.
This is an extension of myers_difference/2 where a diff_script function can be given in case it is desired to compute nested differences. The function may return a list with the inner edit script or nil in case there is no such script. The returned inner edit script will be under the :diff key.
Examples
iex> List.myers_difference(["a", "db", "c"], ["a", "bc"], &String.myers_difference/2)
[eq: ["a"], diff: [del: "d", eq: "b", ins: "c"], del: ["c"]]
pop_at(list, index, default \\ nil)
Specs
pop_at(list(), integer(), any()) :: {any(), list()}
Returns and removes the value at the specified index in the list.
Negative indices indicate an offset from the end of the list. If index is out of bounds, the original list is returned.
Examples
iex> List.pop_at([1, 2, 3], 0)
{1, [2, 3]}
iex> List.pop_at([1, 2, 3], 5)
{nil, [1, 2, 3]}
iex> List.pop_at([1, 2, 3], 5, 10)
{10, [1, 2, 3]}
iex> List.pop_at([1, 2, 3], -1)
{3, [1, 2]}
replace_at(list, index, value)
Specs
replace_at(list(), integer(), any()) :: list()
Returns a list with a replaced value at the specified index.
Negative indices indicate an offset from the end of the list. If index is out of bounds, the original list is returned.
Examples
iex> List.replace_at([1, 2, 3], 0, 0)
[0, 2, 3]
iex> List.replace_at([1, 2, 3], 10, 0)
[1, 2, 3]
iex> List.replace_at([1, 2, 3], -1, 0)
[1, 2, 0]
iex> List.replace_at([1, 2, 3], -10, 0)
[1, 2, 3]
starts_with?(list, prefix)
Specs
starts_with?([...], [...]) :: boolean()
starts_with?(list(), []) :: true
starts_with?([], [...]) :: false
Returns true if list starts with the given prefix list; otherwise returns false.
If prefix is an empty list, it returns true.
Examples
iex> List.starts_with?([1, 2, 3], [1, 2])
true
iex> List.starts_with?([1, 2], [1, 2, 3])
false
iex> List.starts_with?([:alpha], [])
true
iex> List.starts_with?([], [:alpha])
false
to_atom(charlist)
Specs
to_atom(charlist()) :: atom()
Converts a charlist to an atom.
Elixir supports conversions from charlists which contains any Unicode code point.
Inlined by the compiler.
Examples
iex> List.to_atom('Elixir')
:Elixir
iex> List.to_atom('🌢 Elixir')
:"🌢 Elixir"
to_charlist(list)
Specs
to_charlist(:unicode.charlist()) :: charlist()
Converts a list of integers representing code points, lists or strings into a charlist.
Notice that this function expects a list of integers representing UTF-8 code points. If you have a list of bytes, you must instead use the :binary module.
Examples
iex> List.to_charlist([0x00E6, 0x00DF])
'æß'
iex> List.to_charlist([0x0061, "bc"])
'abc'
iex> List.to_charlist([0x0064, "ee", ['p']])
'deep'
to_existing_atom(charlist)
Specs
to_existing_atom(charlist()) :: atom()
Converts a charlist to an existing atom. Raises an ArgumentError if the atom does not exist.
Elixir supports conversions from charlists which contains any Unicode code point.
Inlined by the compiler.
Examples
iex> _ = :my_atom
iex> List.to_existing_atom('my_atom')
:my_atom
iex> _ = :"🌢 Elixir"
iex> List.to_existing_atom('🌢 Elixir')
:"🌢 Elixir"
iex> List.to_existing_atom('this_atom_will_never_exist')
** (ArgumentError) argument error
to_float(charlist)
Specs
to_float(charlist()) :: float()
Returns the float whose text representation is charlist.
Inlined by the compiler.
Examples
iex> List.to_float('2.2017764e+0')
2.2017764
to_integer(charlist)
Specs
to_integer(charlist()) :: integer()
Returns an integer whose text representation is charlist.
Inlined by the compiler.
Examples
iex> List.to_integer('123')
123
to_integer(charlist, base)
Specs
to_integer(charlist(), 2..36) :: integer()
Returns an integer whose text representation is charlist in base base.
Inlined by the compiler.
Examples
iex> List.to_integer('3FF', 16)
1023
to_string(list)
Specs
to_string(:unicode.charlist()) :: String.t()
Converts a list of integers representing code points, lists or strings into a string.
To be converted to a string, a list must either be empty or only contain the following elements:
- strings
- integers representing Unicode code points
- a list containing one of these three elements
Notice that this function expects a list of integers representing UTF-8 code points. If you have a list of bytes, you must instead use the :binary module.
Examples
iex> List.to_string([0x00E6, 0x00DF])
"æß"
iex> List.to_string([0x0061, "bc"])
"abc"
iex> List.to_string([0x0064, "ee", ['p']])
"deep"
iex> List.to_string([])
""
to_tuple(list)
Specs
to_tuple(list()) :: tuple()
Converts a list to a tuple.
Inlined by the compiler.
Examples
iex> List.to_tuple([:share, [:elixir, 163]])
{:share, [:elixir, 163]}
update_at(list, index, fun)
Specs
update_at([elem], integer(), (elem -> any())) :: list() when elem: var
Returns a list with an updated value at the specified index.
Negative indices indicate an offset from the end of the list. If index is out of bounds, the original list is returned.
Examples
iex> List.update_at([1, 2, 3], 0, &(&1 + 10))
[11, 2, 3]
iex> List.update_at([1, 2, 3], 10, &(&1 + 10))
[1, 2, 3]
iex> List.update_at([1, 2, 3], -1, &(&1 + 10))
[1, 2, 13]
iex> List.update_at([1, 2, 3], -10, &(&1 + 10))
[1, 2, 3]
wrap(term)
Specs
wrap(term()) :: maybe_improper_list()
Wraps term in a list if this is not list.
If term is already a list, it returns the list. If term is nil, it returns an empty list.
Examples
iex> List.wrap("hello")
["hello"]
iex> List.wrap([1, 2, 3])
[1, 2, 3]
iex> List.wrap(nil)
[]
zip(list_of_lists)
Specs
zip([list()]) :: [tuple()]
Zips corresponding elements from each list in list_of_lists.
The zipping finishes as soon as any list terminates.
Examples
iex> List.zip([[1, 2], [3, 4], [5, 6]])
[{1, 3, 5}, {2, 4, 6}]
iex> List.zip([[1, 2], [3], [5, 6]])
[{1, 3, 5}]
© 2012 Plataformatec
Licensed under the Apache License, Version 2.0.
https://hexdocs.pm/elixir/1.9.4/List.html