How it Works

How the first_list Script Works

  • Watch the animation as it steps through the first_list script and displays variable values and data. (Or view full size with play/pause control: list-how-it-works.mp4.)
  • Pay careful attention to the index values, and how they control which string gets stored by the color variable and displayed.


In the script, clist = ['green', 'yellow', 'red'] creates a list with three items: clist[0] is 'green', clist[1] is 'yellow', and clist[2] is 'red'.  The value of the index variable starts at zero.  Inside the while True loop, color = clist[index] stores 'green' in color when index is 0, 'yellow' in color when index is 1, or 'red' in color when index is 2.  Each time through the loop, index = index + 1 increases the value of index by 1.  Before repeating the loop, if index >= len(clist) statement compares the value of index to the number of elements in the list.  When index reaches 3, the statement evaluates to true, and index is set back to 0.

Try This: Lists the Easier Way

Yes, there is an easier way!  A for color in clist: loop will automatically copy each successive item in clist into the color variable.  If your script just needs to cycle through items in a list, this is the way to go!

  • Modify the script as shown below.
  • Save your work as first_list_try_this.
  • Flash it into the micro:bit.

 

  • Click the Open Serial button.
  • Verify that the output matches the first example.