Enum with an index

elixir, lists, enum – Sep 22 2018

Iterating over a list and knowing the index or position of that item can be useful. Especially in situations where you know you need to perform some action or update some event.

• • •

If you need an index value associated with a list, use Enum.with_index/2

# I have a list
list = ["a", "b", "c"]

# with_index returns the enumerable with each element
# wrapped in a tuple alongside its index.
iex > Enum.with_index(list)
# [{"a", 0}, {"b", 1}, {"c", 2}]

# Provide an offset and you start at 1 instead of 0
iex > Enum.with_index(list, 1)
# [{"a", 1}, {"b", 2}, {"c", 3}]

Keep in mind you will get a list of tuples with the element and the index value inside of it (as shown above).

When you are looping over a list you can use comprehension to get both the item and index.

for {item, index} <- Enum.with_index(list) do
  "#{item} is at index #{index}"          
end

# ["a is at index 0", "b is at index 1", "c is at index 2"]

# Pass in the offset and start at 1 instead of 0
for {item, index} <- Enum.with_index(list, 1) do
  "#{item} is at index #{index}"          
end

# ["a is at index 1", "b is at index 2", "c is at index 3"]

Source: Elixir documentation

Follow on Twitter
Follow on Github