If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Lesson 9: Lists

# Iterating over lists with loops

AP.CSP:
AAP‑2 (EU)
,
AAP‑2.O (LO)
,
AAP‑2.O.1 (EK)
,
AAP‑2.O.2 (EK)
,
AAP‑2.O.3 (EK)
In programming, we use lists to store sequences of related data. We often want to perform the same operation on every element in a list, like displaying each element or manipulating them mathematically. To do that, we can use a loop to iterate over each element, repeating the same code for each element.

## The need for iteration

Let's make a program to tell the world how to make a Peanut Butter & Banana sandwich, and store the recipe steps in a list.
Here's what that could look like in JavaScript:
``````var  steps = ["Slice bread", "Smear peanut butter on bread", "Place sliced bananas on bread"];
println(steps[0]);
println(steps[1]);
println(steps[2]);``````
What if we then add a very important fourth step to the list, drizzling honey on top?
``var  steps = ["Slice bread", "Smear peanut butter on bread", "Place sliced bananas on bread", "Drizzle honey on top"];``
We would then need to add another line of code at the end to display it:
``println(steps[3]);``
In fact, every time we add a new step, we'd need to add another line of code to display that step!
Fortunately, there's a better way: iterating over the list with a loop.
Here's what that looks like in JavaScript, using a `for` loop:
``````for (var i = 0; i < steps.length; i++) {
println(steps[i]);
}``````
That code will display every single element of the list, no matter how many there are. Let's break down how it works.
The 3-part loop header controls how many times it repeats:
• `var i = 0`: This initializes the counter variable `i` to 0. In JavaScript, the first element in an array has an index of 0, so that is always the start value for a loop that iterates through an array from start to finish.
• `i < steps.length`: This condition checks to make sure that the counter variable `i` is less than the length of the `steps` array. Programming languages always provide a way to find out the length of the array, and in JavaScript, you can find out with the `array.length` property.
• `i++` : This is executed after each iteration of the loop, and adds one to the counter variable. If we added two, we'd only process every other element. Adding one ensures we process every element once.
The body of the `for` loop contains the code that will be run for each iteration. In this case, it's a single line of code that displays the current element:
``println(steps[i]);``
There's one really important thing to notice about this line of code: the index inside the brackets isn't a number like 0 or 1 or 2. Instead, it's the counter variable `i`. That means that the index will change each time this code is run, starting with 0, then 1, then 2. Imagine what would happen if we accidentally wrote steps[0] instead: we'd just be slicing lots of bread! Not so tasty.
✏️ The program below embeds that code and loop. Add more steps to my recipe, or make it a recipe for something completely different. 🌮🍔🥗
📝 See similar code in: App Lab | Snap | Python

## Iteration with computation

Of course, we can do much more than simply display the elements in a list!
For example, we can compute new values based on all the values in the list.
This code computes a total price based on a list of prices of individual products:
``````var totalPrice = 0;
var prices = [1.75, 3.50, 4.99, 2.50];
for (var i = 0; i < prices.length; i++) {
totalPrice += prices[i];
}``````
Run code | 📝 See similar code in: App Lab | Snap | Python
Let's get a bit fancier: we can use conditionals inside a loop to compute values based on which elements satisfy a condition.
This code computes the number of freezing temperatures in a list of temperatures from a 10-day period:
``````var numFreezing = 0;
var temps = [29, 33, 31, 30, 28, 33, 35, 34, 32, 28];
for (var i = 0; i < temps.length; i++) {
if (temps[i] <= 32) {
numFreezing++;
}
}``````
Run code | 📝 See similar code in: App Lab | Snap | Python
We could even create an entirely new list while iterating through a list.
This code processes a list of prices as well, like the first example, but it instead calculates the discounted price of each item (25% off) and adds that price to a new list:
``````var prices = [39.99, 29.99, 19.99];
var discountedPrices = [];
for (var i = 0; i < prices.length; i++) {
var newPrice = prices[i] * 0.75;
discountedPrices.push(newPrice);
}``````
Run code | 📝 See similar code in: App Lab | Snap | Python

## Out of bounds

Consider a list with 8 elements, like this one storing the planets of our solar system:
``var planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"];``
In JavaScript (and any language that uses 0-based indexing), the first element is `planets[0]` and the eighth element is `planets[7]`.
What would this code display, then?
``println(planets[8]);``
In JavaScript, it displays `undefined`. In many languages, it causes a runtime error, preventing the rest of the code from running. In Python, you'll see a "list index out of range" error and in Java, you'll see "java.lang.ArrayIndexOutOfBoundsException".
We never want to cause an out of bounds error in any language, so as programmers, we need to be make sure we specify in-bounds indices for our lists.
Here's a `for` loop with an out of bounds error:
``````for (var i = 0; i <= planets.length; i++) {
println(planets[i]);
}``````
It looks very similar to the correct `for` loop from before, but there's one tiny but crucial difference. Do you see it?
The condition in the header uses `<=` instead of `<` when comparing `i` to `planets.length`. That means the loop will execute when `i` equals `planets.length`. In this case, that's when `i` equals 8. However, as we've just discussed, `planets[8]` is `undefined`. In languages with 0-based indices, the highest index is `array.length - 1`, not `array.length`.
To prevent programmers from causing an out of bounds error, many programming languages provide specialized `for` loops designed just for iterating through lists, known as `for-each` loops.

## List iteration in pseudocode

This pseudocode represents iterating through each element in a list:
``````FOR EACH value IN list
{
<instructions>
}``````
Notice that there is no index in this `FOR EACH` loop, since the `value` of each element is directly available. That means we don't need to worry about out of bounds errors in our pseudocode for list iteration. Phew!
Here's the pseudocode equivalent for displaying each of the 8 planets:
``````planets ← ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

FOR EACH planet IN planets
{
DISPLAY(planet)
}``````
This pseudocode computes the total price from a list of prices:
``````totalPrice ← 0
prices ← [1.75, 3.50, 4.99, 2.50]
FOR EACH price IN prices
{
totalPrice ← totalPrice + price
}``````
This pseudocode counts the number of freezing temperatures:
``````numFreezing ← 0
temps ← [29, 33, 31, 30, 28, 33, 35, 34, 32, 28]
FOR EACH temp IN temps
{
IF ( temp ≤ 32)
{
numFreezing ← numFreezing + 1
}
}``````
This pseudocode creates a new list of discounted prices:
``````prices ← [39.99, 29.99, 19.99]
discountedPrices ← []
FOR EACH price IN prices
{
newPrice ← price * 0.75
APPEND(discountedPrices, newPrice)
}``````

## Want to join the conversation?

• Does JavaScript have a for-each loop?
• This is in no way helpful, but I need an answer:
Who eats PB&Banana instead of PB&J?
• From the author:Me! I love it. I usually add some honey as well. I did recently try PB&J and that's pretty good too, so now I eat PBB&J (peanut butter banana and jam). More steps to iterate over! :)
• In the last example, the list is of prices. Shouldn't the code be newPrice ← prices * 0.75 ?
• From the author:The pseudocode uses a "FOR EACH" loop that specifies the list to iterate through and a variable name to refer to each item in the list:

``FOR EACH price IN prices``

In this case, the list is named `prices` and the variable name for each item is `price`.

The code inside the loop references a variable named `price` since that's the individual item in the list.
• What's the difference between for-loop and while-loop
• A for-loop will iterate for an explicit and definitive number of iterations. For example, in the code:

``for (let i = 0; i < 5; i++) {    console.log('Hello');}``

It is explicit that "Hello" will be printed five times. A while-loop can also be used in a similar manner, for example, you can have a while-loop like below:

``let i = 0;while (i < 5) {    console.log('Hello');    i++;}``

The above loop will also execute five times, and that is clear to the developer reading the code. However, while-loops tend to come in handy when you are not sure how many times a loop will execute. Consider the example below:

``let userInput = 'no';while (userInput === 'no') {    userInput = prompt('Continue? (yes/no):');}console.log('Welcome to our website!');``

In the above instance, you are not certain for how many loops the user will enter 'no' when prompted to continue forward, and thus there is no definitive number of iterations. In situations like this, you will gravitate toward using a while-loop. If you definitively know how many iterations the loop will perform, you will gravitate toward a for-loop.
• Is a data table in App Lab considered a list?
• I wrote a code similar to one of the examples, but the result wasn't as expected. Can someone look at the code and see what's wrong.I used the push and splice functions to see if the code works.

var prices=[10,20,30,40];
var totalprice=0;
for (var i=0; i<prices.length; i++) {
totalprice+=prices[i];
}
println("Total Price = "+"\$"+totalprice);

//using push and splice functions
prices.push(100);
prices.splice(3,0,100);
//expected result = \$300

println("after \$200 added to prices array = "+"\$"+totalprice);
//result came out the same, \$100. I checked the prices.length function on its own, and the values added were stored but not included in the total price calculation.
``let prices = [10, 20, 30, 40];let totalPrice = 0;for (let i = 0; i < prices.length; i++) {      totalPrice += prices[i];}println("Total Price = \$" + totalPrice);// Using push and splice functionsprices.push(100);prices.splice(3,0,100);// Expected result = \$300totalPrice = 0;for (let i = 0; i < prices.length; i++) {      totalPrice += prices[i];}println("after \$200 added to prices array = \$" + totalPrice);``