Traversing and Modifying a List
We can traverse through a list using a for loop. There are two options: loop through the VALUES, or loop through the INDICES.
Two ways to traverse
We can traverse through a list using a for loop. There are two options: loop through the VALUES, or loop through the INDICES.Both print the same thing, so far. The difference only shows up when you try to CHANGE the list.
Modifying a list
Consider the following code that is intended to change all even numbers in a list to 0.The loop variable x holds a COPY of the value, not the slot it came from. Assigning to x replaces that copy and the list never hears about it. On the next pass x is handed the following value, and the change is lost.
Here's the correct code to change all even numbers in a list to 0. Compare it to the previous one.
Creating a list
If you want to create a list containing the first five perfect squares, then you can complete these steps in three lines of code.The list starts empty and grows by one on each pass. This is the accumulator pattern from the previous unit, with a list in place of a running total.