Jeśli widzisz tę wiadomość oznacza to, że mamy problemy z załadowaniem zewnętrznych materiałów na naszej stronie internetowej.

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

Główna zawartość

Lekcja 8: Listy

# Iterating over lists with loops

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)
}``````

## Chcesz dołączyć do dyskusji?

Na razie brak głosów w dyskusji
Rozumiesz angielski? Kliknij tutaj, aby zobaczyć więcej dyskusji na angielskiej wersji strony Khan Academy.