A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Iterating Over Collections

College Depth 77 in the knowledge graph I know this Set as goal
530topics build on this
328prerequisites beneath it
See this on the map →
Array Indexing and BoundsFor Loops+1 moreNested Loops and Multi-Level Iteration
loops iteration collections

Core Idea

Looping through a collection processes each element. Index-based loops are traditional; many languages provide for-each/enhanced-for loops that iterate directly over elements. Choosing the right loop style improves clarity.

How It's Best Learned

Write loops using both index-based and for-each styles; count total iterations to verify loops process all elements; test with empty collections.

Common Misconceptions

That all loops work the same way (index-based, for-each, while each have tradeoffs); that modifying a collection while iterating is safe (it can cause elements to be skipped or revisited); that loop variables after iteration have a defined value (it varies).

Explainer

You already know how to write for loops that count through a range of numbers, and you know how to access individual elements in a collection by index. Iterating over a collection combines these skills: instead of manually accessing `items[0]`, then `items[1]`, then `items[2]`, you use a loop to process every element automatically. This is one of the most common patterns in all of programming — nearly every program that works with data needs to examine, transform, or filter a collection of items.

The index-based approach uses a counting loop to step through positions: `for i in range(len(items))` in Python, or `for (int i = 0; i < items.length; i++)` in Java/C. Inside the loop, you access each element as `items[i]`. This gives you full control — you know exactly which position you are at, you can skip elements, go backwards, or access neighboring elements like `items[i-1]`. But it is also verbose and error-prone: off-by-one errors (starting at 1 instead of 0, or using `<=` instead of `<`) are among the most common bugs in programming.

The for-each style (also called an enhanced for loop or iterator-based loop) simplifies this: `for item in items` in Python, or `for (String item : items)` in Java. You get each element directly without managing an index variable. The code is shorter, clearer, and eliminates off-by-one errors entirely. The tradeoff is that you lose direct access to the index — you cannot easily say "give me the element two positions ahead" or "replace the current element." When you need both the element and its position, many languages offer a compromise like Python's `enumerate()`: `for i, item in enumerate(items)` gives you both.

One critical rule: do not modify a collection while iterating over it. If you remove an element from a list mid-loop, the remaining elements shift positions, causing the loop to skip the next element or crash with an error. If you add elements, the loop may process them unexpectedly or run forever. The safe approach is to build a new collection with the desired elements (filtering), or collect indices to modify and apply changes after the loop finishes. This constraint applies to both index-based and for-each loops, though the failure modes differ — index loops silently skip elements while for-each loops in many languages raise an explicit error.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesComparison Operators and Boolean TestsLogical Operators and Boolean AlgebraConditional StatementsWhile LoopsFor LoopsArrays and ListsArray Indexing and BoundsIterating Over Collections

Longest path: 78 steps · 328 total prerequisite topics

Prerequisites (3)

Leads To (1)