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()
Here is the script from the Try This section on the previous page [1] 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'.
Links
[1] https://learn.parallax.com/tutorials/language/python/led-lights/intro-lists/how-it-works