Lecture 15 — For Loops

Basics

  • for loops tend to have a fixed number of iterations computed at the start of the loop.

  • while loops tend to have an indefinite termination, determined by the conditions of the data.

  • Most Python for loops are easily rewritten as while loops, but not vice-versa.

Overview of Today

  • Ranges and control of for loop iterations

  • Nested loops

  • Lists of lists

Part 1: Range in For Loops

  • range() is a function to generate a sequence of integers:

    for i in range(10):
        print(i)
    

    outputs digits 0 through 9 in succession, one per line.

    • Remember that this is up to and not including the end value specified!

  • A range is not quite a list — instead it generates values for each successive iteration of a for loop.

  • If we want to start with something other than 0, we provide two integer values:

    >>> list(range(3, 8))
    [3, 4, 5, 6, 7]
    
  • With a third integer values we can create increments. For example:

    >>> list(range(4, 20, 3))
    [4, 7, 10, 13, 16, 19]
    

    starts at 4, increments by 3, stops when 20 is reached or surpassed.

  • We can create backwards increments:

    >>> list(range(-1, -10, -1))
    [-1, -2, -3, -4, -5, -6, -7, -8, -9]