15.4. Working with Indexes

Sometimes, we don’t want to access all of the items in a list one at a time in order. 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.


Lists and their indices

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


In programming, we often count from 0 instead of from 1. It will take some getting used to, but when you see a list of things, remember that the first one it item 0. The last item will always have an index one less than the number of items - the last item in a list with 10 values is index 9.

You can read and write the values of 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.

Activity: CodeLens 15.4.3 (cspcollectionsintro_listindexes3)

We can even use a variable that names a number as the index for an item. This sample uses itemNum to identify which value we want from the list. As we change itemNum, the item we access by using it as an index changes as well:

Activity: CodeLens 15.4.5 (cspcollectionsintro_listindexes5)

This trick will come in very handy later when we write more complex logic for accessing all of the items in a list.

Finally, just like with a string, we can find the length of a list by using the len function. We can either use it in the same way we would use any other numeric value by doing more work with it or giving the value a name to work with later:

Activity: CodeLens 15.4.6 (cspcollectionsintro_listindexes6)

You have attempted of activities on this page