Intro to Lists

In the next activity, you will be adding a third LED light, and then turning them on/off in custom sequences.  It’s true that you could extend the coding approach you used for two LEDs, but there’s a better way: lists.  (We'll practice lists using a serial terminal first, so there is no circuit needed for this activity).

About Lists

A list is a sequence of items contained between brackets, like this:

clist = ['green', 'yellow', 'red']

A script can access an item in a list by using the item's index value, starting with 0 from left to right. So, the index of 'green' is 0, 'yellow' is 1, and 'red' is 2.  The instruction print(clist[2]) would display the word "red" in a serial terminal.  A script can also change items a list using index values. For example, to change clist[1] from 'yellow' to 'blue' you would use clist[1] = 'blue'.

In this activity, you will use lists to display different sequences of printed colors in the terminal.  In the next activity, you will instead use the lists to make the colored lights display in various sequences.

There are different ways to display items in a list. This activity will start by displaying items in a list “the hard way” because it’s good to get familiar with how to access items in a list by their index values.  The Try This section introduces “the easy way” to access each item in a list with a loop that does the indexing for you.  Last, but not least, the Did You Know and Your Turn sections show how to use your script to change, append, and display the contents of lists.  

Script: first_list

This first script repeatedly displays this in the python.microbit.org Serial terminal.  

color = green
color = yellow
color = red  

  • Set the project name field to first_list.
  • Enter script below into the micro:bit Python Editor, and then click Save.
  • Click Send to micro:bit.
# first_list

from microbit import *

clist = ['green', 'yellow', 'red']
index = 0

while True:
    color = clist[index]
    print('color =', color)
    sleep(1000)
    index = index + 1
    if index >= len(clist):
        index = 0
        print()


Tests

  • Click the Show seriaal button to open the serial monitor.
    (See Use the Serial Monitor.)
  • Verify that the color = green, color = yellow, color = red sequence displays repeatedly in the terminal.