Week 7 · Session 1

Lists That Change

Replacing an item, adding to the end, and building a list from nothing.

Replace an Item by Position

  • colors[1] = "amber" puts a new item where "yellow" was
  • The list is the same length afterward. Only that one position changed
  • A position past the end cannot be assigned either: colors[3] = "blue" is the same IndexError

append: Add to the End

  • colors.append("blue") adds one item after the last one
  • len(colors) goes up by one, and the new item sits at position len(colors) - 1
  • One item per call. Three items is three calls, or one call inside a loop

Try It: Grow a List

  • Replace position 0 with "white" and print the list again
  • Append one more color, then print colors[4]

              

Start Empty, Fill With a Loop

  • pattern = [] is a list with nothing in it yet. len(pattern) is 0
  • A loop that calls append once per trip leaves one item per trip in the list
  • This is how a program turns a series of answers from the user into one list it can play back

Try It: Build It

Predict both printed lines before you press Run.

  • Change 4 to 6 and predict again
  • Append step * 2 + 1 instead. What does the list hold now?

              

Positions Come From People, Too

  • A person says light 2. The list calls that position 1. So the light they mean is leds[choice - 1]
  • A person says light 4 and there are three: leds[3] raises IndexError
  • Check the number before you use it: if 1 <= choice <= len(leds):

Try It: Off by One

  • Remove the - 1 and read the error
  • Put it back and set choice to 1. Which item prints?
  • Wrap the print in an if so it only runs when choice is between 1 and len(lights). Then try choice = 4

              

A List of Pins Is Still a List

  • leds = [Pin(15, Pin.OUT), Pin(14, Pin.OUT), Pin(13, Pin.OUT)]
  • leds[0].on() lights the first one. leds[choice - 1].on() lights the one a person asked for
  • for led in leds: visits every light, and len(leds) says how many there are
  • Wire three more and add them to the list. Nothing else in the program changes

Back to Lab 4

  • Spotlight lights the one a person asked for: leds[choice - 1], after a range check
  • Your Own Pattern builds a list with append inside a loop, then lights it
← Exit
1 / 10