Working with Indexes

To access individual items in a collection (a list or a string), we can use an index. Each item in a collection has a number associated with it – think of it as the item’s address in the collection. The first item in a collection has index 0, the next one 1, and so on. See the image below for a view of two lists with the index for each list item shown at the top of each yellow box and the value for that index shown at the bottom of each yellow box.

../_images/listIndices.png

Figure 2: Lists and their indicies

We use square brackets to access items of the list, e.g., myList[0] will return the first item in the list.

    csp-16-4-1: What is the last index for the list myFirstList?
  • 0
  • This is the index of the first item in the list.
  • 1
  • This is the index of the second item in the list.
  • 2
  • This is the index of the last item in this list since it contains 3 items and the first index is 0.
  • 3
  • The length of this list is 3, but the first index is 0 so the 3rd item is at index 2.
    csp-16-4-2: What is the value of the item at index 3 in mySecondList?
  • 12
  • This is the value at index 0.
  • "ape"
  • This is the value at index 1.
  • 13
  • This is the value at index 2.
  • 321.4
  • This is the value at index 3.

You can access individual items of a list just like they were variables. Using list[index] on the right side of an assignment returns the value at that index in the list. Using list[index] on the left side of an assignment statement changes the value at that index in the list.

(Items_As_Variables)

    csp-16-4-3: Of the four items in the list named items, which one is not changed in the program above?
  • items[0]
  • Originally, items[0] was 2, but then we set it to the string: "First item"
  • items[1]
  • We set items[1] to be the same as items[0]: "First item"
  • items[2]
  • We incremented items[2] in line 4.
  • items[3]
  • The value at items[3] doesn't change. It still equals 8.

    csp-16-4-4: What would the following code print?

    values = [3, 2, 1]
    values[0] = values[1]
    values[2] = values[2] + 1
    print(values)
    
  • [3, 2, 1]
  • That is the original contents of values, but the contents are changed.
  • [2, 0, 2]
  • When you set values[0] to values[1] it makes a copy of the value and doesn't zero it out.
  • [2, 2, 2]
  • The value at index 0 is set to a copy of the value at index 1 and the value at index 2 is incremented.
  • [2, 2, 1]
  • Notice that we do change the value at index 2. It is incremented by 1.
Next Section - Reversing a List