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.


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.

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.

Activity: CodeLens 3 (Items_As_Variables)

You have attempted of activities on this page