AlgoCademy
Lesson
Code

Exceeding List Bounds in {lang}


When accessing list data with indices, the most common problem we can run into is exceeding the list's bounds.

Remember, the items of a list are normally indexed from 0 to length - 1.

Any index which is strictly greater than length - 1 is invalid.

When you try to access an item with an invalid index, {lang} throws an error:

myList = [1, 2, 3]

# Valid indices: 0, 1, 2
print(myList[0]) # Output: 1
print(myList[2]) # Output: 3

# Invalid indices: 3, 30
print(myList[3]) # IndexError
print(myList[30]) # IndexError

Each of the last 2 accesses will produce an IndexError: list index out of range.


Negative indices:

Remember that in {lang}, we can also access items of a list using negative indices.

The valid negative indices are between -length and -1.

Any index which is strictly less than -length is invalid:

myList = [1, 2, 3]

# Valid indices: -1, -2, -3
print(myList[-1]) # Output: 3
print(myList[-3]) # Output: 1

# Invalid indices: -4, -10
print(myList[-4]) # IndexError
print(myList[-10]) # IndexError

Each of the last 2 accesses will produce an IndexError: list index out of range.

As programmers, we always want to make sure that we don't exceed one array's bounds in our programs


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.