Zip Lists Together


Did You Know: zip() Function

Sometimes, a Python script needs a loop to access each successive item in more than one list.  For example, maybe each color has a corresponding on-time in a different list.  When used in place of in range(), Python’s zip() function makes this easy.  Here’s an example:

# lists_with_zip

from microbit import *

color_list  = ['green', 'yellow', 'red']
time_list   = [ 1000,    200,      500]

for color, time in zip(color_list, time_list):
    print('color:', color, '| time:', time)

print('Done!')

The first time through the loop, the color variable stores 'green', while the time variable stores 1000.  The second time through, color is 'yellow',  and time is 200.  The third time through, color is 'red' and time is 500.  Each time through the loop,  print('color:', color, '| time:', time) displays both variables.
 


Your Turn: Add a Times List

Now that you’ve seen how to use a single loop with the zip() function to access related items in more than one list, let’s try it with custom LED on-times.

  • Click Open and reopen led_blink_list.hex.
  • Set the project name field and line-1 comment to led_blink_list_your_turn.
  • Modify the script as shown below, then click Save.
  • Click Send to micro:bit.
  • Check to make sure that the green light stays on for about a second, the yellow light stays on for about 1/5th of a second, and the red light stays on for about half a second.