Welcome back, you've seen the accumulator pattern before.
Now, we're going to accumulate a list, instead of a number.
So in this code example,
as with all accumulator patterns,
we have to have some sequence that we're going to generate over.
In this case, we have
variable nums and we are binding to a list containing three, five, and eight.
We're now going to accumulate a list.
We'd like that list to contain the squares of all the numbers from the original list;
so nine, 25, and 64.
As with all accumulated patterns,
you have some accumulator variable.
I'm going to call it accum.
We could call it something else, maybe squares,
would probably be a reasonable choice.
Anyway, it's called accum here and we initialize it to be just an empty list.
This is typical when we're accumulating list.
We start with an empty list and we're going keep appending to it.
This is the analog of starting with zero.
When you're going to take an accumulation that gives you a sum,
we start with the empty list and then on line three,
we start our iteration.
So we're going to iterate each time w is going to be bound to one of the items from nums.
In the first iteration,
w will be bound to three.
We'll set x to be the square of three or nine and
then we're going to append the current value of x nine into the accumulator.
On the second iteration,
w gets bound to the second value five and so x gets
bound to 25 and we
append 25 the third time.
W is eight, x is 64.
Sixty four gets appended to the list.
So this is following the same logic of your accumulator pattern
before each time through this iteration.
An additional item is going to be appended into accum and so really
accum is the squares so far that we've managed to accumulate.
When we're done with this iteration,
we are finished with all three of these,
can printout accum, and accum will have all of the squares.
So let's run it and sure enough we get nine,
25 and 64 at the end.
So it was a little check on your understanding.
Let me try changing one thing in this,
suppose that I indent that print.
Can you predict what the output will be?
A good chance to pause and see if you can predict it.
At each stage, we're now going to not just
change the contents of the accumulator but we're going
to print what we've accumulated so far.
So we're now going to have three lines of output.
First just the list nine and then list with nine and 25,
and the list with nine, 25, and 64.
So as before, this is a useful debugging strategy with
the accumulator pattern is to print out what you've accumulated so
far and see how it grows over time.
So in summary, to accumulate later list,
you will initialize the accumulator to be an empty list.
You'll iterate and at each iteration,
you will append a new item.
At the end, volla,
you've have accumulated a new list. Catch you later.