Accessing Array Elements

In the previous exercise, we learned how to create an array. Now let's look at how to access individual elements of an array.

Each element in an array has an index, which is its position in the array. Indexes in an array start from zero. This means that the first element has an index of 0, the second element has an index of 1, and so on.

Let's look at an example:

newYearResolutions = ["Keep a journal", "Attend a falconry course", "Learn to juggle"]

In this example, "Keep a journal" is at index 0, "Attend a falconry course" is at index 1, "Learn to juggle" is at index 2.

If we want to access the first element in the array newYearResolutions and print it, we use the following syntax:

print(newYearResolutions[0]) # Output: 'Keep a journal'

Similarly, we can access other elements in the array and print them:

print(newYearResolutions[1]) # Output: 'Attend a falconry course'
print(newYearResolutions[2]) # Output: 'Learn to juggle'

Or we can store the value in a variable:

firstResolution = newYearResolutions[0]

Instructions

Store one colleague from the colleagues array into a variable named favoriteColleague.

Print the value of the variable favoriteColleague.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/10

Accessing Array Elements | Start Coder