List Comprehension with Counter in Elixir

List Comprehension with Counter in Elixir

Is there a way to add loop counter to the comprehension?

For example, the comprehension without counter:

for c <- ["a", "b"], do: c            # => ["a", "b"]

How can I add counter to it? Something like this:

for c <- ["a", "b"], do: {counter, c} # => [{0, "a"}, {1, "b"}]

1 Answer

Use Enum.with_index:

iex(1)> for {value, index} <- Enum.with_index(["a", "b"]), do: {value, index}
[{"a", 0}, {"b", 1}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.