0..(n - 1) isn't empty when n is 0

A common way to loop over the indexes of a list is for i <- 0..(length(list) - 1). If the list is empty, you might expect that loop will not run. But actually it runs twice.

Elixir counts down when the last value is smaller than the first, so the range has two elements:

list = []

Enum.to_list(0..(length(list) - 1))
#=> [0, -1]

To prevent this, add an explicit positive step of 1:

list = []

Enum.to_list(0..(length(list) - 1)//1)
#=> []

list = [:a]
Enum.to_list(0..(length(list) - 1)//1)
#=> [0]

Since Elixir 1.18, such a range without a step emits a deprecation warning, but it still returns [0, -1].

← All notes