iq.lab
Python starts when a code cell comes near or you run one
01 Python, one step at a time

Lesson 2 of 6

Walking a list

A for loop visits every item in a list, one at a time. Keep one or two values in a notebook as you go, and running totals, counts and maximums all turn out to be the same small program.

About 1 hour 50 minutes, with the 2 problems worked in it
By the end you can
  • Trace a for loop over a list and say the value of every name after each pass

  • Write a loop that keeps a running total, a count or a running maximum

  • Pick a safe starting value for a running maximum

  • Keep two notebook values that work together, such as the current streak and the best streak

  • Loop over positions with range and enumerate when you need the index

  • Use a while loop when the walk does not move one item at a time

You have four days of order counts: [12, 30, 7, 25]. What was the most orders on any one day? In SQL you would write SELECT MAX(orders), and in Python you could call max(orders). Both are fine at work.

In an interview, the question is almost never the plain maximum. It is which day was busiest, or the biggest jump from one day to the next, or the longest streak of good days. No single built-in answers those. What answers them is a short loop that walks the list and keeps a few notes, and that loop is the most important program in this course. Every pattern later on, from hash maps to dynamic programming, is this same loop with a smarter notebook.

Module 0 used this loop to count and to find the largest number. This lesson takes it apart one line at a time and builds its family: totals, counts, maximums, positions, and walks that stop early.

One item at a time

What does a for loop actually do? A for loop takes the items of a list one at a time, in order, and runs the indented lines under it once for each. Those indented lines are the loop's body, and one run of the body is one pass. Here is the smallest version. The trace below shows the code on one side and every name and value on the other. Press Next to move one line at a time.

Step throughVisiting every item
Step 1 of 12
Line 1 is about to run.
orders = [12, 30, 7, 25]
for x in orders:
print(x)
print("done")
Names
no names yet
Output
(nothing printed yet)

Three things to notice, because they cause most loop confusion:

  • x is a name, not a box in the list. Each pass, Python moves the tag x to the next item. Writing x = 0 inside the loop would move the tag (rebinding, from the last lesson) and leave the list alone.
  • The body is whatever is indented under the for line. Line 4 is not indented, so it runs once, after the loop.
  • The loop decides when to stop. You do not count; it runs out of items.

The next program tests the first of those. Predict it before you check.

PredictTwice each item?

Read the loop and type exactly what it prints, one line per print. A list prints in square brackets, like [1, 2].

nums = [3, 1, 4]
for x in nums:
    x = x * 2
    print(x)
print(nums)

A notebook that remembers

Printing each item is not useful by itself. Useful loops remember something as they go. The names a loop keeps up to date as it walks are its notebook, module 0's word for them. For the total orders over the four days, the notebook is one number that grows as we walk.

Step throughA running total
Step 1 of 13
Line 1 is about to run.
orders = [12, 30, 7, 25]
total = 0
for x in orders:
total = total + x
print(total)
Names
no names yet
Output
(nothing printed yet)

Read line 4 with the rule from the last lesson: work out the right side first, then point the name on the left at the result. total = total + x is an instruction, not an equation: "the new total is the old total plus x". The shorthand total += x does the same, and you will see both.

The idea that makes loops hard to get wrong is the promise: a sentence about the notebook that is true at the end of every pass. Here:

Check it against the trace: after two passes, total is 42, and the items visited so far are 12 and 30. When the loop ends, the items visited so far are all of them, so the promise turns into the answer. Interviewers call a promise like this an invariant, and you will use this argument for every algorithm in this course.

Work it outThe notebook mid-walk

The running-total loop from the trace runs on a new list, [5, 9, 4, 6], with total starting at 0. What is total right after the third pass? Type a whole number.

total

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Counting is the same loop with a condition. How many days had more than 20 orders? The notebook is a count, and it grows only when the item passes a test. if x > 20: runs the line indented under it only when x > 20 is True; lesson 3 covers if in full.

count = 0
for x in orders:
    if x > 20:
        count += 1

Here is the state after each pass on [12, 30, 7, 25]:

Passxx > 20?count after the pass
112no0
230yes1
37no1
425yes2

The promise: after each pass, count is how many visited items were above 20. After the last pass that is 2, the answer.

Now put a counting loop together yourself. The lines are shuffled, and two of them do not belong.

Put in orderCount the even numbers

Put the lines in order to build count_evens(nums), which returns how many numbers in nums are even. Indentation is already part of each line. Two of the lines do not belong.

A number is even when dividing it by 2 leaves no remainder: x % 2 == 0.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • if x % 2 == 0:
    • count = 0
    • count += 1
    • return count
    • count = 0
    • for x in nums:
    • def count_evens(nums):
    • return count

    The next problem keeps a running total and also builds a new list as it walks. In the last lesson, append added one box to the end of a list. Inside a loop it runs once per pass, so the list grows by one item each time. This short trace writes twice each order count into a new list. Guess what it prints before you step through.

    Step throughA list that grows as the walk goes
    Step 1 of 11
    Line 1 is about to run.
    orders = [12, 30, 7]
    out = []
    for x in orders:
    out.append(x * 2)
    print(out)
    Names
    no names yet
    Output
    (nothing printed yet)

    The promise: after each pass, out holds twice each item visited so far, in order. The problem below keeps two notebook values: the running total, and the list of totals written down so far. Try it before you open the hints.

    easyLoops and basicsPrefix sums target 15 min

    Running sum

    Given a list of numbers nums, return a new list of the same length where the item at position i is the sum of nums[0] through nums[i].

    Example 1
    Inputnums = [1, 2, 3, 4]Output[1, 3, 6, 10]

    1, then 1 + 2, then 1 + 2 + 3, then 1 + 2 + 3 + 4.

    Example 2
    Inputnums = [3, -1, 2]Output[3, 2, 4]
    Constraints
    • 0 ≤ len(nums) ≤ 105

    • -106 ≤ nums[i] ≤ 106

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The running maximum

    Back to the opening question: the most orders on any one day. The notebook is one number, best, the largest count seen so far. Each pass asks one question: is this item bigger than the best so far? If yes, it becomes the new best.

    You stepped through this loop in module 0. It is the loop every later pattern grows from, so here it is again on new numbers. This time the loop sits inside a function, largest, and the trace calls it on [3, 8, 2, 9, 4]. The call gets its own box of names on the right, and return best hands the answer back.

    Before you step through, guess: how many times does best change?

    Step throughFinding the largest number
    Step 1 of 18
    Line 1 is about to run.
    def largest(nums):
    best = nums[0]
    for x in nums:
    if x > best:
    best = x
    return best
    Names
    no names yet
    Output
    (nothing printed yet)

    Here is the whole idea in the four questions this course asks of every algorithm:

    Why start at nums[0]? The start value must not break the promise. nums[0] is a number from the list, so after the first pass best is the largest of the one number visited. It is tempting to start at 0 instead. Does that work? Find the lists that break it.

    Quick checkWhen does a start of 0 fail?

    This version starts the notebook at 0:

    def largest(nums):
        best = 0
        for x in nums:
            if x > best:
                best = x
        return best

    For which lists does it return a wrong answer? Choose every one that does.

    Choose every option that applies, then check.

    float("-inf") is the other safe start. It is negative infinity, a float smaller than every number (the mirror of float("inf") from the last lesson), so the first item always replaces it. Run this, then change the second line to best = 0 and run it again.

    ⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

    It prints -3. With best = 0 it prints 0, a number that is not in the list.

    One more question an interviewer wants you to ask out loud: what if the list is empty? On [], nums[0] raises IndexError (no box at position 0), and the float("-inf") version quietly returns -inf. Neither is an answer. You ask ("can the list be empty, and what should I return then?") and handle it with one check at the top, such as if len(nums) == 0: return None. Raising edge cases before anyone asks is part of the bar for an L4 round.

    Now write the mirror image yourself.

    Code itThe smallest number

    Write smallest(nums), which returns the smallest number in a non-empty list. Use a loop, not the built-in min: the point is the walk. Then press Watch it run to see your notebook change.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Two notes at once

    Some walks need two notebook values that work together. Take the longest streak: in a list of 0s and 1s, the length of the longest unbroken run of 1s. One note is current, the length of the run that ends at the item we are on. The other is best, the longest run seen so far. A 1 makes current one longer, and then best checks whether that run is a new record. A 0 breaks the run, so current goes back to 0.

    Two pieces of Python make this short. else: gives an if a second branch: its lines run exactly when the test is false, so every pass runs one branch or the other, never both. This prints busy for 30, then quiet for 7:

    for x in [30, 7]:
        if x > 20:
            print("busy")
        else:
            print("quiet")

    The second piece: max(a, b) returns the larger of two values, so best = max(best, current) is a one-line version of "if current > best, set best = current".

    Work out both notes for [1, 1, 0, 1] on paper first: after each item, what are current and best? Then step through to check.

    Step throughTwo notes: the current run and the best run
    Step 1 of 21
    Line 1 is about to run.
    bits = [1, 1, 0, 1]
    current = 0
    best = 0
    for b in bits:
    if b == 1:
    current += 1
    best = max(best, current)
    else:
    current = 0
    print(best)
    Names
    no names yet
    Output
    (nothing printed yet)

    current drops back to 0 at every 0; best never goes down. The answer is best, 2. The promise has two halves: after each item, current is the number of 1s in a row ending at that item, and best is the longest run among the items visited.

    Now put the two notes in a function for a new question: the longest streak of busy days, days with more than 20 orders. The lines are shuffled, and two of them do not belong.

    Put in orderThe longest busy streak

    Put the lines in order to build longest_busy(orders), which returns the length of the longest run of busy days in a row, where a busy day has more than 20 orders. longest_busy([25, 30, 7, 22]) is 2. Indentation is already part of each line. Two of the lines do not belong.

    current = best = 0 sets both notes to 0 in one line.

    Your program

    Add lines from the list below, in order.

      Unused lines (some do not belong)
      • current = 0
      • current = best = 0
      • if x > 20:
      • for x in orders:
      • def longest_busy(orders):
      • best = current
      • best = max(best, current)
      • current = 0
      • else:
      • return best
      • current += 1

      This is a classic warm-up, and warm-ups matter: candidates report that a fast, clean first problem banks time for the harder follow-up.

      easyLoops and basics target 15 min

      Longest run of ones

      A list bits holds only 0s and 1s. Return the length of the longest unbroken run of 1s.

      Example 1
      Inputbits = [1, 1, 0, 1, 1, 1]Output3

      The last three items are a run of three 1s.

      Example 2
      Inputbits = [1, 0, 1, 1, 0, 1]Output2
      Constraints
      • 1 ≤ len(bits) ≤ 105

      • Every item is 0 or 1.

      Plan it first

      Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

      ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
      Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

      When you need the position

      Often the question is not the largest value but where it is: which day was busiest? for x in nums hands you the items but not their positions. Two tools give you positions.

      range(n) produces the whole numbers 0, 1, ..., n − 1: it stops before n. So range(len(nums)) produces every valid position of nums, and nums[i] reads the item there. range(4) is 0, 1, 2, 3, exactly the positions of a four-item list.

      The trace keeps the position of the busiest day so far in best_day. Two arrows under the list show where i and best_day point. Before you step through, guess what it prints.

      Step throughThe busiest day, by position
      Step 1 of 14
      Line 1 is about to run.
      orders = [12, 30, 7, 25]
      best_day = 0
      for i in range(len(orders)):
      if orders[i] > orders[best_day]:
      best_day = i
      print(best_day)
      Names
      no names yet
      Output
      (nothing printed yet)

      The notebook holds a position, not a count. The count is read through it, as orders[best_day]. The promise: after each pass, orders[best_day] is the largest count among the days visited so far.

      Positions start at 0. The second day is position 1. Keep that translation in your head; off-by-one mistakes come from forgetting it.

      What if two days tie? > moves the notebook only for a strictly bigger count, so on [12, 30, 7, 30] this loop keeps best_day at 1, the earlier 30. When a problem says which of the tied days it wants, the comparison decides it.

      enumerate gives you the position and the item together. for i, x in enumerate(orders): gives i = 0, x = 12, then i = 1, x = 30, and so on. (The i, x on the left unpacks two values into two names; lesson 5 shows how.) Here is the busiest day with it:

      best_day = 0
      for i, x in enumerate(orders):
          if x > orders[best_day]:
              best_day = i

      Same walk, same notebook, same answer: 1. Reach for enumerate when the body needs both the position and the item.

      Positions also let you look at neighbors. The change from one day to the next is orders[i] - orders[i - 1]. At i = 0 that would read orders[-1], the last item, so the walk must start at position 1. range(a, b) starts at a and stops before b, so range(1, len(orders)) gives 1, 2, 3 on the four days.

      PredictPositions and neighbors

      Type exactly what this prints, one line per print. print(a, b) puts one space between the two values.

      orders = [12, 30, 7, 25]
      for i in range(1, 4):
          print(i, orders[i] - orders[i - 1])
      
      Code itThe biggest jump

      Write biggest_jump(orders), which returns the largest increase from one day to the next: the largest value of orders[i] - orders[i - 1]. The list has at least two days. If orders only ever fall, the answer is the least-bad change, which is negative.

      ⌘+Enter runsPython starts when a code cell comes near or you run one
      Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

      While loops: walking at your own pace

      A for loop moves exactly one item per pass and stops at the end of the list. A while loop checks a condition before every pass and stops the first time the condition is false. Nothing moves unless a line in the body moves it.

      Use it when the walk is not "every item once": when it should stop partway, at a condition, or when two positions move inward from both ends of a list (module 4). (Lesson 3 shows another way to stop early: return inside a for loop.) Here we find the first day with more than 20 orders and stop there. The arrow i under the list marks the position being checked. Before you step through, guess what it prints.

      Step throughStop at the first busy day
      Step 1 of 9
      Line 1 is about to run.
      orders = [12, 7, 30, 25]
      i = 0
      while i < len(orders) and orders[i] <= 20:
      i += 1
      print(i)
      Names
      no names yet
      Output
      (nothing printed yet)

      The promise: every day before position i had 20 or fewer orders. It is true at the start, when no day comes before position 0, and each i += 1 steps past a day the condition has just checked. So when the loop stops on a busy day, that day is the first one.

      The order inside the condition matters. a and b is true only when both sides are true. Python checks the left side first and skips the right side when the left is false (lesson 3 covers and). So i < len(orders) guards orders[i]. If no day were busy, i would reach 4, the left check would fail, and Python would never try orders[4], which does not exist. The loop would print 4, the length of the list, which is how the code says no day qualified.

      Check the "none found" case yourself: the same loop on a list with no busy day.

      PredictNo busy day at all

      The loop from the trace runs on a list where no day has more than 20 orders. Type exactly what it prints.

      orders = [5, 9, 3]
      i = 0
      while i < len(orders) and orders[i] <= 20:
          i += 1
      print(i)
      

      Now write a while loop of your own. The walk stops at a condition, so you decide what the condition is and which line moves the walk toward it.

      Code itDays the budget pays for

      You pay for days in order, starting with the first, and each day has a cost. Write days_paid(costs, budget), which returns how many days you can pay for before the next day would take the total spent over budget. Stop at the first day that does not fit, even if a later day is cheaper. Use a while loop. Then press Watch it run to see the walk stop.

      For [4, 3, 5, 2] and a budget of 10 the answer is 2: the first two days cost 7, and the third would make 12.

      ⌘+Enter runsPython starts when a code cell comes near or you run one
      Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

      Last, practice saying it. The words you write here are the words you will say in the room.

      Say itSay it like you would in the room

      Explain, as you would to an interviewer before typing, how you would return the position of the busiest day in a list of daily order counts. Say what you would ask first, then cover the walk, the notebook, the promise and the cost in a few plain sentences.

      A few sentences first: 0 of 60 characters.

      Saved in this browser as you type.

      Next: Decisions and functions