Other Data Types in Lists


Did You Know: Other Data Types in Lists

Even though you have been working with lists of strings, lists can contain other data types, like int, and a microbit.pin object.  Different types can even appear in the same list.  

my_list = [‘yellow’, 1000, pin14]

Lists can be changed after they are created.  In Python-speak, the term is mutable.  Here are some ways to change lists in a script:

clist[1] = 'blue'         # replaces 'yellow' to 'blue'

clist.append('yellow')    # adds 'yellow' as the last item in the list

clist.index('red')        # finds the first instance of 'red' in the
                          # list and returns the index

Your application can even use both list items and their index values in a list; here is an example that uses a for loop.  Note how it uses len(clist) instead of 3.  The len(clist) call returns the length of the list.  It is currently 3, but if you added items to the list, the result of a call to len(clist)would automatically increase.  

   for index in range(len(clist)):
        color = clist[index]
        print('index:', index, ', color:', color)
        sleep(1000)
    print()

Here is another example that uses enumerate instead of in range.  Enumerate returns 2 values (a tuple) that contains the index number in the list and the item.  In this example, the index number gets copied to the variable named index, and the color string (‘green’, ‘yellow’, or ‘red’) gets copied to the variable named color.

       for index, color in enumerate(clist):
        print('index:', index, ', color:', color)
        sleep(1000)
    print()    

Your Turn

Here is the script from the Try This section on the previous page  with statements from the Did You Know section above added.  It replaces 'yellow' with 'blue', adds 'yellow' after 'red', and gets the index of 'red'.

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

 

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

 

  • Use the tips in the Try This section at the bottom of the previous page to modify your script so that it displays both the index and the color.
  • Verify your solution by making sure the terminal displays this after clicking Open Serial.
  • Name your script first_list_your_turn_with_index, and save your work as a .hex file after debugging to get it to work.