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.
We use square brackets to access items of the list, e.g.,
myList will return the first item in the list.
- This is the index of the first item in the list.
- This is the index of the second item in the list.
- This is the index of the last item in this list since it contains 3 items and the first index is 0.
- The length of this list is 3, but the first index is 0 so the 3rd item is at index 2.
csp-16-4-1: What is the last index for the list
- This is the value at index 0.
- This is the value at index 1.
- This is the value at index 2.
- This is the value at index 3.
csp-16-4-2: What is the value of the item at index 3 in mySecondList?
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.
itemswas 2, but then we set it to the string:
- We set
itemsto be the same as
- We incremented
itemsin line 4.
- The value at
itemsdoesn't change. It still equals 8.
csp-16-4-3: Of the four items in the list named
items, which one is not changed in the program above?
- [3, 2, 1]
- That is the original contents of
values, but the contents are changed.
- [2, 0, 2]
- When you set
valuesit 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.
csp-16-4-4: What would the following code print?
values = [3, 2, 1] values = values values = values + 1 print(values)
Discuss topics in this section with classmates.