Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a List with a for-loop

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.

like image 880
0xAffe Avatar asked Nov 20 '15 15:11

0xAffe


People also ask

What is for loop in Python list?

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.

How to use for loop to iterate over a 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.

What are the different elements of a for-loop?

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.

How do you add elements to a list in Python?

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.


1 Answers

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

like image 57
Gazler Avatar answered Oct 17 '22 08:10

Gazler