Repository navigation
Enumerate with index
Joel Meador edited this page Jun 8, 2026
·
1 revision
In Elixir, how can I access the index of each element as I enumerate over a list?
When passing in a list into an Enum function like Enum.map/2, the index of each element is not available by default.
The key is to use Enum.with_index/2! This function returns the enumerable with each element wrapped in a tuple alongside its index.
iex> Enum.with_index([:a, :b, :c])
[{:a, 0}, {:b, 1}, {:c, 2}]By passing the enumerable returned from with_index/2 into Enum.map/2, the index will then become available as the second argument of the callback function.
iex> list = Enum.with_index([:a, :b, :c])
iex> Enum.map(list, fn {k, v} -> {k, -v} end)
[{:a, 0}, {:b, -1}, {:c, -2}]The with_index function can also be called within the function argument itself:
iex> Enum.map(Enum.with_index([:a, :b, :c])fn {k, v} ->
...> {k, -v}
...> end)
[{:a, 0}, {:b, -1}, {:c, -2}]This can also fit nicely into a pipe chain:
iex> [:a, :b, :c]
...> |> Enum.with_index()
...> |> Enum.map(fn {k, v} ->
...> {k, -v}
...> end)
[{:a, 0}, {:b, -1}, {:c, -2}]🏳️🌈🦄 Sharing is caring. 🦄🏳️🌈
TODO: can we recreate the tag system here roughly with sections about certain subjects?