Why can't I fill a list with this simple for-loop?
new_data = []
for data <- old_data do
new_data = List.insert_at(new_data, -1, data)
end
After this operation my new_data
list is still empty, even though the loop is N times executed.
Python List is a collection of items. For loop can be used to execute a set of statements for each of the element in the list. In this tutorial, we will learn how to use for loop to traverse through the elements of a given list.
For loop can be used to execute a set of statements for each of the element in the list. In this tutorial, we will learn how to use for loop to traverse through the elements of a given list. In general, the syntax to iterate over a list using for loop is element contains value of the this element in the list.
The other elements, such as curly braces, indentation, placing the expression and the closing curly brace on a new line, the white space between the head and the body of a for-loop, are not compulsory yet strongly recommended.
To populate a list this way, you create a for loop which will iterate over the way you want to create each element. 00:38 Then, in the same loop, call .append () to add that element to the existing list. 00:45 Here’s one example, creating a list of square roots of a collection of values.
In Elixir, you can't mutate the value your variable is referencing as explained in Are Elixir variables really immutable?. For in this instance is not a "loop" it is a list comprehension.
You can assign to the result of a comprehension with:
new_data = for data <- old_data do
data
end
In your line:
new_data = List.insert_at(new_data, -1, data)
The new_data
variable is local to the scope of the comprehension. You can use your previous new_data
value, but you won't be able to rebind for the outside scope. Which is why new_data
is still []
after your comprehension. The scoping rules are explained in http://elixir-lang.readthedocs.org/en/latest/technical/scoping.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With