Syllabus Lesson 5 of 246 · Module 1: Python for this course
Module 1: Python for this course

Lists and loops over real data

Why it matters A neural network is mostly loops over lists of numbers. If you can total, filter and count a list, you can read most training code.

Say you logged your steps for a week: [4200, 8100, 12000, 3000, 9500, 10100, 7600]. Two questions you might ask: how many steps in total, and on how many days did you reach a goal of 8,000?

See it

A loop visits the items one at a time. You keep a running number and update it on each visit, like a tally on paper.

total = 0
for s in steps:      # s is 4200, then 8100, then 12000 ...
    total = total + s

After the first visit total is 4200, after the second 12300, and so on.

Running total: a variable you start at zero and add to on every pass through the loop.

Counting is the same idea, except you add 1 only when a condition is true: if s >= goal: count = count + 1.

Recap Start a number, loop, update it. That pattern is how a network adds up its loss over a dataset.

Your turn

Write two functions:

  • total_steps(steps) returns the sum of the list.
  • days_at_goal(steps, goal) returns how many days are at or above goal.

Use a loop for both (no sum()), so you practise the pattern.

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.