Learn
Lists
Accessing Elements in a List

A collection is of no use to us if we can’t access or work with its contents. In order to access the elements within a list, we must reference the element’s “index”. An index represents a numerical position within a list.

val oakIslandArtifacts = listOf("Lead cross", "Rhodolite garnet brooch", "Gold brooch")

Here’s a breakdown of the indices of the above list elements:

Element Index
“Lead cross” 0
“Rhodolite garnet brooch” 1
“Gold brooch” 2

Notice how the count begins with 0 and not 1; this is because Kotlin is a zero-based language and the count in every Kotlin collection begins with 0.

Keeping these indexed-positions in mind, we can construct the following syntax to access an element:

listName[index]

The name of the list is followed by square brackets which contains the index of the element we need to access. Applying this pseudo code to our previous list, we can access each element as such:

oakIslandArtifacts[0] // Lead cross oakIslandArtifacts[1] // Rhodolite garnet brooch oakIslandArtifacts[2] // Gold brooch

Each statement can be wrapped in a println() statement to see its output or stored in a variable for later use.

Note: Attempting to access an element within an index that does not exist will result in an error. For instance, if there are 2 elements within a list, and the specified index is 5, the compiler will throw the following Out of Bound error:

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 2

Instructions

1.

Every year, the United States hosts hundreds of marathons, some of which have made it into the list of top 10 marathons worldwide. In Marathon.kt, we’ll create a list containing some of the most popular ones.

Declare a variable, unitedStatesMarathons and in it store an immutable list containing the following marathon names:

  • "Boston Marathon"
  • "Bank of America Chicago Marathon"
  • "TCS NYC Marathon"
  • "Marine Corps Marathon"

Fun Fact: About 0.5% percent of the U.S. Population has run a full marathon. 🏃‍♀️

2.

Access "Bank of America Chicago Marathon" using square brackets and its index in the list. Wrap this code in a print statement to see the output.

Folder Icon

Take this course for free

Already have an account?