Iterating Over Arrays with Index Counters
A for-each loop is an alternative form of the for loop that makes it easier to visit every value in an array or collection.
Try it: What a for Loop Hands You
What a Python for loop gives its loop variable from each kind of iterable: the characters of a string, the positions from range(len(word)), the elements of a list, (index, item) pairs from enumerate(), the numbers of range(start, stop, step), a dict's keys, its .values() and its .items() tuples unpacked into key, val, the inner lists of a nested list and the values an inner loop visits; and why removing items from a list while looping over it skips the next item, while looping over a copy nums[:] does not.
How it works
- The for statement asks the object for an iterator, then calls next() on it once per pass.
- Each next() result is bound to the loop variable (a tuple result such as ('a', 10) or (0, 'red') is unpacked into two names), and the indented body runs once with it.
- A string gives characters, a list gives element values (not positions), range() computes start, start + step, … stopping before stop, and a dict gives its keys in insertion order (.values() the values, .items() key-value tuples).
- A nested list's inner list is one element of the outer loop; a second, inner for loop is needed to visit the values inside it.
- A list iterator only remembers a position number into the live list: removing an item shifts the later items left, so the item that slides into the passed position is skipped. Looping over a copy (nums[:]) keeps the positions fixed.
- When next() has nothing left the loop ends (StopIteration) and the loop variable keeps its last value; an empty iterable runs the body zero times.
Default run (10 steps): A 3-line program. Step through it: each pass of the for loop asks the iterator for its next item, binds the loop variable to it and runs the indented body once. … Done: the loop body ran 3 times. Output: red | green | blue.
Simplified: The programs are twelve fixed templates: you choose the loop and edit only its data (a short string, list items that are words or integers, key: value pairs with word keys and integer values, range numbers from -20 to 20, up to 4 rows of integers, up to 10 numbers). Nothing you type is executed: the lab's own small parsers turn it into literals, and a model of CPython's iterator protocol written for these loops runs the program. Every program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables before every line, the printed output, the final variables and the error.
Loading the simulation…
Predicting a Loop Before Reading the Explanation
Programs very often need to do the same thing to every item in a collection. If you have an array of names and want to print each one, the usual approach is a for loop that counts from zero up to the array length and fetches each item by its position. That pattern is so common that Java offers a shorter form built for exactly this job, called the for-each loop. This article teaches you to read that shorter form, to predict what it prints, and to find the point where a loop's output stops matching your expectation.
Before reading any explanation, look at the loop below. It prints every value in an array of Strings. Run it in your head first and decide what appears on the screen and in what order. The sections that follow show how the loop reaches each value, so you can check your prediction against the reasoning.
What do you think happens?
What does this loop print, and in what order?
Reveal answer
Ana, Ben, Chloe, one per line, in array order
The loop visits the array from its first stored value to its last. Each pass makes name hold the next value, and println prints that value. The printed text is the stored value itself, not a position number.
Reading the For-Each Header
The general form of a for-each loop is written as a type, then a variable name, then a colon, then the array or collection to be walked through. The body, written in curly braces, is repeated once for each element. In the example above, the type is String, the variable is name, and the array is namelist.
A helpful way to read the header aloud is: for each String, called name, in the array namelist, do the following. The colon is read as the word in or from. Read this way, the header describes a traversal. The loop visits the array in turn, and at each visit a single value is made available under the name you chose.
- 1Read the type after the opening parenthesis. It declares the kind of value the loop variable will hold, and it must match the element type of the array.
- 2Read the identifier after the type. It is the name you choose for the variable that receives one value on each pass.
- 3Read the part after the colon. It names the array or collection the loop walks through.
- 4Read the body in curly braces. It runs once for every value in the collection, using the current value of the loop variable.
Tracing the Loop One Value at a Time
The easiest way to build a reliable prediction is to trace the loop one pass at a time. Each trip around the loop makes the loop variable hold a new value, and the body runs with that value. The loop checks whether values remain, not whether a counter has reached a number. The diagram below shows the progression for the namelist array with three names.
Predicting output for a different array
Suppose the array is int[] scores = {7, 3, 9, 3}, and the loop is for (int score : scores) followed by System.out.println(score). What prints?
- 1Read the header
The type is int, the variable is score, and the collection is scores. The loop will visit every element of scores in order.
- 2Count the elements
The array holds four values, so the body runs four times. The number of passes equals the number of stored values, not a counter you set yourself.
- 3Track the variable
Pass 1 gives score the value 7, pass 2 gives 3, pass 3 gives 9, and pass 4 gives 3 again. Repeated values are visited each time they are stored.
- 4Apply the body
The body prints score on each pass, so the printed lines match the stored values in order.
The output is 7, 3, 9, 3, one per line. The value 3 appears twice because it is stored twice.
What the Loop Variable Actually Holds
A for-each loop is an alternative form of the for loop that makes it easier to visit every value in an array or collection.
The loop control variable holds one value from the array on each pass. It is not an index. It represents one of the values stored in the array, not the position where that value lives. This is the most important fact about the loop, because it changes how you think about every line inside the body. If you want the number 2 to appear on screen, you must have an index of 2, not a loop variable that happens to hold 2. In the name example, the variable holds the strings Ana, Ben, and Chloe. It never holds 0, 1, or 2.
Comparing Index Counters with For-Each Loops
Consider printing the same array with each form. The for-each version needs only the header and the body. The traditional version must declare a counter, state where it starts, state when it stops, and fetch each element by its position. Both produce the same output for this task, but they reach the elements in different ways.
Ana
Ben
Chloe
Ana
Ben
Chloe| Feature | Traditional for loop | For-each loop |
|---|---|---|
| Header contents | Counter, start, stop, and step | Type, variable, colon, collection |
| How elements are reached | Fetched by index position | Received directly as values |
| Index available | Yes, through the counter | No index appears |
| Best fit | Tasks that need position information | Tasks that visit every value |
Two ways to visit every element of an array
Locating Where Output Diverges
When a for-each loop's output differs from what you expected, the failure is usually in one of three places: the header, the body, or the data in the array. Working through these in order narrows the search quickly.
- 1Check the header first. Confirm that the type after the opening parenthesis matches the element type of the array, and that the array after the colon is the one you meant to traverse.
- 2Then examine the body. It runs once per value, so a line that looks harmless may run far more often than you assumed.
- 3Finally, check the array contents. The loop faithfully reports whatever the array holds, so a surprising line of output often reflects an unexpected stored value.
Common mistake Treating the loop variable as a position number
What it looks likefor (String name : namelist) { System.out.println(name + " is at position " + name); }Why it failsThe loop variable holds a value from the array, not an index. Using it as a position produces nonsense or a compile error.
Do this insteadUse a traditional for loop with an integer counter when you need the position.
Common mistake Writing a for-each header with the wrong element type
What it looks likeint[] scores = {7, 3, 9}; for (String s : scores) { ... }Why it failsThe type in the header must match the element type of the array, so this header does not describe the stored values.
Do this insteadUse for (int s : scores) for an array of int values.
Common mistake Traversing the wrong array after the colon
What it looks likeString[] names = {...}; String[] cities = {...}; for (String c : names) { ... } when you meant to visit citiesWhy it failsThe loop walks through exactly the collection named after the colon, so the output reflects that array.
Do this insteadCheck the name after the colon against the array you intended to print.
Common mistake Assuming the loop runs a fixed number of times instead of once per stored value
Practice Tracing a Loop
Trace this loop without running it. Write down every line it prints, in order, then check your answer. The array is String[] fruits = {"Fig", "Kiwi", "Lime", "Pear"}; and the loop is for (String f : fruits) { System.out.println(f.length()); }. Predict what prints, and identify the iteration where a naive guess about the output would go wrong.
Hints
- Count the stored values first. The number of passes equals the number of elements, which is four here.
- The body prints
f.length(), which is a number, not the text itself. Check whether the printed value is the stored string or a count of its characters. - Fig has three characters, Kiwi has four, Lime has four, and Pear has four.
Change the loop above so it prints the position of each fruit as well as its name, then explain which loop form you chose and why the for-each form cannot do this job on its own.
Hints
- The position is information the for-each header does not provide.
- A traditional for loop with an integer counter can supply the position directly.
Key Takeaways
- A for-each loop is an alternative form of the for loop that visits every value in an array or collection, using the header for (Type variable : array) and a body that runs once per value.
- The loop control variable holds one value from the array on each pass. It is not an index, and no array index appears in a for-each loop.
- A traditional for loop reaches elements through an integer counter and position, while a for-each loop receives each value directly, so use the traditional form whenever position information is needed.
- When output differs from your prediction, check the header, then the body, then the array contents, in that order.