From your initial question I think you are missing a key difference between Python and Elixir. Elixir variables are immutable and you cannot modify them like you would in Python.
results = [] # <= create empty array
for x in range(1, 100):
if 10 <= x <= 20:
results.append(x) # <= append to the `results` array which is outside the `for` loop
else:
# skip x
# results = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
incorrectly translated to Elixir (similar to your initial attempt)
results = [] # <= create an empty array
Enum.each(1..100, fn x ->
if x >= 10 and x <= 20, do: results = results ++ [x] # <= does NOT append to the `results` list
end)
# warning: variable "results" is unused (there is a variable with the same name in the context, use the pin operator (^) to match on it or prefix this variable with underscore if it is not meant to be used)
instead should be written
results = Enum.reduce(1..100, [], fn x, acc -> # <= assign the final value of the accumulator to results
if x >= 10 and x <= 20 do
acc ++ [x] # <= append x to the accumulator
else
acc # <= do not modify the accumulator
end
end)
# results = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
The difference is that Enum.reduce builds up the accumulator array and then assigns it all to results at the end, it doesn’t modify results as it processes each element of the list.
In fact, it cannot modify results even if we wanted to.
The full solution then looks like this,
list1 = [
[1, 2, 3, 4, "nil"],
[6, 7, 8, 9, 10],
[11, "nil", 13, "nil", 15],
[16, 17, "nil", 19, 20]
]
final_list = Enum.reduce(list1, [], fn inner_list, acc ->
acc ++ Enum.reduce(inner_list, [], fn x, acc2 ->
if x >= 10 and x <= 20 do
acc2 ++ [x]
else
acc2
end
end)
end)
# => [10, 11, 13, 15, 16, 17, 19, 20]
If you don’t need to retain the nested structure or process the elements further, I would suggest a different approach. First flatten the inner lists and then filter with a simple boolean test.
final_list = list1
|> List.flatten()
|> Enum.filter(&(&1 >=10 and &1 <= 20))
# final_list = [10, 11, 13, 15, 16, 17, 19, 20]






















