Computer Programming 1 (Python) • Core Data Structures

Iterating Lists — I can iterate over a list to compute results (totals, counts) using for loops at my level.

Learn to walk through every item in a list and build up totals, counts, and other computed results with Python for loops.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Computers were originally built to process large amounts of data quickly — far faster than any human could manage with pen and paper. In the earliest days of computing, programmers needed a way to tell the machine to repeat the same operation over and over for every piece of data in a collection. This idea of iteration — systematically visiting each item in a sequence — became one of the most fundamental concepts in all of programming.

1945 • First Stored-Program Loops

Early computers like ENIAC required physical rewiring to repeat instructions. The concept of a stored-program loop — instructions that jump back to an earlier point — transformed computing.

1957 • FORTRAN's DO Loop

FORTRAN, the first widely-used high-level language, introduced the DO loop — a structured way to iterate a fixed number of times over arrays of numerical data.

1991 • Python's for-in Loop

Guido van Rossum designed Python with a clean, readable for-in syntax that iterates directly over the elements of a list, removing the need for index-based counters in most cases.

2000s • Data Science Explosion

As data sets grew into millions of records, iterating over lists to compute totals, averages, and counts became the bread and butter of data analysts working in Python.

The central question that iteration solves is straightforward: how do you take a collection of data — say, a list of test scores — and reduce it to a single useful result like a total, a count, or an average? Python's for loop gives you an elegant, readable answer.

SECTION 2

Core Principles & Definitions

Before you start writing loops, you need to understand a handful of foundational ideas. These principles apply every time you iterate over a list in Python, whether you are adding up numbers, counting how many items meet a condition, or finding the largest value.

1

List

An ordered collection of items stored in square brackets, such as [85, 92, 78, 95]. Each item has a position (index) starting at 0.
2

For Loop

A control structure that automatically walks through every element in a list, one at a time. The syntax is for item in my_list: followed by an indented body.
3

Loop Variable

The temporary variable (like item) that takes on the value of the next element each time the loop repeats.
4

Accumulator Pattern

A variable initialized before the loop (e.g., total = 0) that is updated inside the loop body to build up a running result.
5

Counting Pattern

A variation of the accumulator where you increment a counter (e.g., count += 1) each time a condition is met inside the loop.
✦

KEY TAKEAWAY

Think of a for loop like a cafeteria checkout line. Each student (element) steps up to the register one at a time. The cashier (your loop body) scans their tray, and a running total on the register (the accumulator) updates with each student. By the time the last student walks through, the register shows the grand total — no student was skipped, and every item was counted.

SECTION 3

Visual Explanation — How a For Loop Walks Through a List

For Loop Iteration Over a Listscores = [85, 92, 78, 95]total = 0for score in scores:total = total + scoreList Elements85index 092index 178index 295index 3Accumulator (total) After Each Iteration850 + 8517785 + 92255177 + 78350255 + 95total = 350
The diagram shows the list [85, 92, 78, 95] across the top. Below, the accumulator variable total starts at 0 and grows with each iteration: 85 → 177 → 255 → 350. Each colored box matches its corresponding list element.

Notice how Python handles the heavy lifting. You do not need to manage an index counter or worry about going past the end of the list. The for loop automatically stops once it has visited every element. Your job is simply to decide what to do with each element inside the loop body — in this case, add it to total. This clean separation between "walking through the list" and "processing each item" is what makes Python's for loop so powerful and readable.

SECTION 4

How the Accumulator and Counter Patterns Work

The two most common patterns when iterating over a list are the accumulator pattern (for computing totals) and the counter pattern (for counting items that meet a condition). Both follow the same three-step structure: initialize, iterate, and use the result.

Accumulator Pattern (Totals)

ACCUMULATOR STRUCTURE

accumulator=0foriteminlist:accumulator=accumulator+itemaccumulator = 0 for item in list: accumulator = accumulator + item

accumulator — a variable that holds the running result. item — the loop variable that takes on each element's value in turn. list — the collection you are iterating over.

Counter Pattern (Counts)

COUNTER STRUCTURE

count=0foriteminlist:ifcondition:count=count+1count = 0 for item in list: if condition: count = count + 1

count — an integer that starts at 0 and increments by 1 each time the condition is true. condition — a Boolean expression that filters which items get counted (e.g., item >= 90).

Computing an Average

AVERAGE FORMULA

average=total/len(list)average = total / len(list)

After accumulating the total with a for loop, divide by the number of elements. Python's built-in len() function returns the length of the list.

⚠

Common Mistake

Always initialize your accumulator or counter before the loop. If you write total = 0 inside the loop body, it resets to 0 on every iteration, and you will only end up with the last element's value.

SECTION 5

Common Iteration Patterns at a Glance

The accumulator and counter are just two members of a larger family of iteration patterns. The table and diagram below summarize the most useful patterns you will encounter in an introductory Python course. Each one follows the same initialize-iterate-use structure but differs in what happens inside the loop body.

PatternInitializeLoop BodyResult
Sum / Totaltotal = 0total += itemSum of all elements
Countcount = 0if cond: count += 1Number of items meeting a condition
Averagetotal = 0total += itemtotal / len(list)
Find Maximummx = list[0]if item > mx: mx = itemLargest element
Build New Listresult = []result.append(item * 2)Transformed copy of original

Five common for-loop iteration patterns in Python

Accumulator vs. Counter FlowchartSTARTtotal = 0 count = 0Initialize accumulatorsMore items?NoENDYesscore = next itemtotal += scoreAccumulator (always runs)if score>=90: count+=1Counter (conditional)
This flowchart shows how both the accumulator and counter execute inside the same loop. The left branch (total += score) runs on every iteration. The right branch (count += 1) only runs when the condition is true. After both branches finish, the loop returns to check for more items.

The key insight from the flowchart is that you can run both an accumulator and a counter inside a single for loop. You don't need separate loops for each computation. This saves time and keeps your code clean.

SECTION 6

Worked Example — Analyzing Test Scores

Let's walk through a complete example. Suppose you have a list of test scores for a class, and you want to find the total, the count of scores that are 90 or above (an "A"), and the class average.

Computing Total, Count of A's, and Average

  1. 1

    Step 1 — Define the Data

    Create the list of scores: scores = [85, 92, 78, 95, 88, 91, 73, 99]. This list contains 8 elements.
  2. 2

    Step 2 — Initialize Accumulators

    Before the loop, set up the accumulator and counter: total = 0 and a_count = 0. Both start at zero so that the first addition produces the correct result.
  3. 3

    Step 3 — Write the For Loop

    The loop header is for score in scores:. Inside the body, add two lines: total += score to accumulate the sum, and if score >= 90: a_count += 1 to count scores that earn an A.
  4. 4

    Step 4 — Trace the Execution

    Iteration 1: score = 85, total = 85, a_count = 0. Iteration 2: score = 92, total = 177, a_count = 1 (92 ≥ 90). Iteration 3: score = 78, total = 255, a_count = 1. Iteration 4: score = 95, total = 350, a_count = 2. Iteration 5: score = 88, total = 438, a_count = 2. Iteration 6: score = 91, total = 529, a_count = 3. Iteration 7: score = 73, total = 602, a_count = 3. Iteration 8: score = 99, total = 701, a_count = 4.
    After 8 iterations: total = 701, a_count = 4
  5. 5

    Step 5 — Compute the Average

    After the loop, compute average = total / len(scores) which is 701 / 8.
    average = 87.625. The class earned 4 A's out of 8 students, with an average score of 87.625.
💡

Pro Tip: Use += for Cleaner Code

The expression total += score is shorthand for total = total + score. Both do the same thing, but += is the conventional style in Python and reduces the chance of typos.

SECTION 7

For Loops vs. Built-In Functions

Python provides built-in functions like sum(), len(), max(), and min() that can sometimes replace a for loop entirely. Understanding when to use each approach is an important programming skill.

ApproachStrengthsLimitations
For LoopFully customizable — can combine totals, counts, conditionals, and complex logic in a single pass through the list.Requires more lines of code. Beginners may introduce bugs by misplacing the initialization or indentation.
Built-in FunctionsShorter, more readable for simple operations. sum(scores) is one line vs. three for a loop.Cannot handle conditional counting or multi-step logic. You would need multiple separate calls for different results.
While LoopUseful when you don't know in advance how many iterations you need (e.g., user input loops).More error-prone for list iteration — you must manually manage the index variable and risk infinite loops.

Comparison of iteration approaches in Python

🔑

WHEN TO USE WHAT

Use sum() and len() when you only need a simple total or count of all items. Switch to a for loop the moment you need conditional logic (like counting only scores above 90) or when you want to compute multiple results in a single pass. Think of built-in functions as power tools for specific jobs and the for loop as a versatile Swiss Army knife.

SECTION 8

Connection to Advanced Techniques

The for loop and accumulator pattern you are learning now form the foundation for more advanced Python features. As you progress, you will encounter shorter and more powerful ways to express the same ideas, but all of them build on the logic you already understand.

What You Know NowAdvanced VersionWhat's New
for item in list:List Comprehensions: [x*2 for x in list]Builds a new list in a single expression instead of using append inside a loop.
Manual counter with ifGenerator with sum(1 for x in list if x > 90)Counts conditionally in a single line using a generator expression.
total += itemfunctools.reduce() with a lambda functionA functional programming approach that applies a function cumulatively to all items.
Index-free iterationfor i, item in enumerate(list):Provides both the index and the value in each iteration.

From basic for loops to advanced Python patterns

Don't worry about mastering these advanced techniques right now. The important thing is to recognize that the simple for loop with an accumulator is not a "beginner trick" you will outgrow — it is the conceptual foundation underneath all of these advanced tools. Understanding why the accumulator pattern works will make it much easier to learn list comprehensions, generators, and functional programming when you are ready.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why the accumulator variable must be initialized before the for loop, not inside the loop body. What would happen if you placed total = 0 as the first line inside the loop?
Show answer
If total = 0 were inside the loop body, it would reset the accumulator to 0 at the start of every iteration. This means the previous sum would be erased each time, and after the loop finishes, total would only hold the value of the last element in the list — not the sum of all elements. By placing the initialization before the loop, the accumulator retains its running total across all iterations, correctly building up the final result.

Question 2: BASIC CALCULATION

Given the list prices = [4.50, 7.25, 3.00, 12.99, 5.75], write a for loop that computes the total cost. What is the final value of total?
Show answer
The code is: total = 0, then for price in prices: total += price. Tracing through: 0 + 4.50 = 4.50, then 4.50 + 7.25 = 11.75, then 11.75 + 3.00 = 14.75, then 14.75 + 12.99 = 27.74, then 27.74 + 5.75 = 33.49. The final value of total is 33.49.

Question 3: INTERMEDIATE

Given temps = [68, 72, 75, 81, 79, 85, 90] (daily temperatures in °F for a week), write a for loop that counts how many days were "hot" (80°F or above) and also computes the average temperature for the week.
Show answer
Initialize total = 0 and hot_days = 0. The loop is: for temp in temps: total += temp and if temp >= 80: hot_days += 1. The sum is 68 + 72 + 75 + 81 + 79 + 85 + 90 = 550. The average is 550 / 7 ≈ 78.57. Days at or above 80 are 81, 85, and 90, so hot_days = 3 and average ≈ 78.57.

Question 4: APPLIED

A teacher stores quiz scores in a list: quizzes = [7, 9, 5, 10, 8, 6, 9, 10, 4, 8]. Each quiz is out of 10 points. Write a program using a for loop that computes: (a) the total points earned, (b) the number of "perfect" scores (10 out of 10), and (c) the percentage score overall (total earned ÷ total possible × 100).
Show answer
Initialize total = 0 and perfect = 0. Loop: for score in quizzes: total += score and if score == 10: perfect += 1. (a) total = 7 + 9 + 5 + 10 + 8 + 6 + 9 + 10 + 4 + 8 = 76. (b) perfect = 2 (the two scores of 10). (c) Total possible = 10 × 10 = 100. Percentage = 76 / 100 × 100 = 76%. You could compute the total possible with len(quizzes) * 10 for a more flexible solution.

Question 5: CRITICAL THINKING

Consider two approaches to finding how many negative numbers are in a list called data. Approach A uses a for loop with a counter. Approach B uses len([x for x in data if x < 0]). Both give the same result, but which one would you choose if data contained one million numbers? Explain why, thinking about what each approach creates in memory.
Show answer
Both approaches produce the correct count, but they differ in memory usage. Approach B (the list comprehension wrapped in len()) first builds an entirely new list of all the negative numbers, stores it in memory, and then counts its length. If there are 500,000 negative numbers out of a million, that temporary list uses significant memory. Approach A (the for loop with a counter) only ever stores a single integer (count), regardless of how many negatives exist. For very large data sets, the for-loop counter is more memory-efficient. An even better one-liner would be sum(1 for x in data if x < 0), which uses a generator instead of building a full list — but the simple for loop remains the clearest and most memory-friendly approach.

SUMMARY

Lesson Summary

Summary

A Python for loop automatically visits every element in a list, assigning each one to a loop variable in turn. To compute a running total, you use the accumulator pattern: initialize a variable to 0 before the loop, then add each element to it inside the loop body using +=. To count items that satisfy a condition, you use the counter pattern: initialize a counter to 0 and increment it inside an if statement within the loop.

You can combine both patterns in a single loop to compute totals, counts, and averages in one pass. While Python's built-in functions like sum() handle simple cases, the for loop remains essential whenever you need conditional logic or multiple results. This pattern is the foundation for list comprehensions, generators, and every advanced iteration technique you will learn later.

Varsity Tutors • Computer Programming 1 (Python) • Iterating Lists — I can iterate over a list to compute results (totals, counts) using for loops at my level.