Care and feeding of lists

In order to keep track of multiple pieces of information at a time, Python uses a data structure called a "list". Lists hold an ordered set of values. Any value that can be stored into a variable can be stored in a list. They can be defined using a simple syntax:

robot> [1, 2, 3]

You can even mix values of different type in a list:

robot> [1, "a", 3]

Furthermore, you can define a list using a variable. When you define the list, Python copies the value stored in the variable into the list:

robot> a = 2
robot> [1, a, 3]
[1, 2, 3]

Lists are just another type of value themselves, and therefore can be stored in a variable:

robot> a = [1, 2, 3]
robot> a
[1, 2, 3]

The real power of the list comes from the ability to use them to automate a task. The robot can take a list and perform an action for each element in it automatically. This is done with a for loop:

for element in [1,2,3]:
  print element

Try this on your robot. Also, try this with a list stored in a variable instead of [1, 2, 3] in this example.

The general form of a for loop is this:

for (variable) in (list):
  (block of code)

Python starts by assigning the first element of (list) into the variable called (variable). Then it executes (block of code), which presumably does something with the value of (variable). Then, it sets the next value in (list) to (variable) and executes (block of code) again. The process repeats until (block of code) has been run for every element of (list).

Define the list colors = ['r', 'g', 'b']. Use this list with a for loop to turn on the red, green and blue lights at once. (Solution)

One nice utility function provided by the robot is range. Calling range(n) returns a list the contains the number from zero to n-1:

robot> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Use range(10) with a for loop to print the numbers from 1-10. Since range(10) will return the numbers from 0-9, you will have to be clever. (Solution)

Not only can you automatically loop through a list, you can pick out individual values easily:

robot> a = ['a', 'b', 'c']
robot> a[1]
'b'

Note that the first element of a list is denoted by [0]. What would range(10)[5] return? (Think about this before doing it!) You can just as easily set values in a list this way:

robot> a = ['a', 'b', 'c']
robot> a[1] = 'q'
robot> a
['a', 'q', 'c']

Unfortunately, you can only set values in the list that are already present. For example, you cannot set a[3].

robot> a = ['a', 'b', 'c']
robot> a.append('q')
robot> a
['a', 'b', 'c', 'q']

Extra list challenges: