← Back to lesson 05: Build a new list

Build a new list: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Bind a list, transform it with `for`, and leave the original value unchanged.

Run a for comprehension that doubles [1, 2, 3], then return both the original and the new list.

Build a new list and keep the old one

for returns a new list. It does not edit numbers.

Original full example
# Draw each value from numbers and collect a doubled value
numbers = [1, 2, 3]
doubled = for value <- numbers do
  value * 2
end

# Return both lists and check the original
{numbers, doubled, numbers == [1, 2, 3]}

doubled is [2, 4, 6].

numbers is still [1, 2, 3].

The final result is {[1, 2, 3], [2, 4, 6], true}.

Steps for the full example

  1. numbers = [1, 2, 3] binds the original list to a name.
  2. value <- numbers draws 1, then 2, then 3. The body calculates a result for each value.
  3. The comprehension collects those results in [2, 4, 6]. It never changes the original list.

Original lesson notes

A binding gives a value a name. In numbers = [1, 2, 3], the name numbers points to that list.

Elixir data is immutable: code does not change the existing list in place. A transformation builds a new list instead.

A for comprehension runs one expression for each value it draws from a collection. In value <- numbers, read <- as “take each value from numbers.”

Symbols and terms
=
Bind the value on the right to the name on the left. The next lesson shows its matching job.
<-
Take each value from the collection on the right, one at a time.
for ... do ... end
Run the body for each drawn value and collect the results in a new list.
==
Compare two values and return true or false.
binding
Giving a value a name, as in numbers = [1, 2, 3].
immutable
An existing value is not changed in place. A transformation creates a new value.
list comprehension
A for expression that visits values and collects a new list of results.

Original full exercise

Use a for comprehension to multiply every value in [1, 2, 3] by 3. Return both the old and new lists.

Exercise starter
numbers = [1, 2, 3]

tripled = for value ____ numbers do
  ____
end

{numbers, tripled}

The result should be {[1, 2, 3], [3, 6, 9]}.

Show hint

Draw values with <-, then calculate value * 3 in the body.

Show original answer
Reference answer
# Build a new list from the old one
numbers = [1, 2, 3]

tripled = for value <- numbers do
  value * 3
end

{numbers, tripled}
After doubled = for value <- numbers do value * 2 end, did numbers change?

No. The comprehension built a new list and bound it to doubled. The original list stayed the same.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references