Length and the Last Element

Often you don't know how many elements a list has. Maybe another part of the program filled it, or the number of elements changes while the program runs (you'll learn to add and remove elements in the next exercises). You can always find out with len() (short for length):

students = ["Jennifer", "Boris", "Nancy", "David", "Ava"]
print(len(students))

This prints:

5

Like print(), len() is a function: a command you use by writing its name and, in parentheses, the value it should work with. len() gives you a number, so you can store it in a variable, calculate with it or print it with a label: print("Students:", len(students)) prints Students: 5.

With len(), you know where the last element is. Indexes start at 0, so the last index is always one less than the number of elements: a list of 5 elements has indexes 0, 1, 2, 3 and 4. The last element is therefore at index len(students) - 1:

print(students[len(students) - 1])

This prints:

Ava

Python first calculates the index in the square brackets (5 − 1 = 4) and then reads the element at that index. A common mistake is to forget the - 1: students[len(students)] asks for index 5, where there is no element, and ends with IndexError: list index out of range.

You need the last element so often that Python has a shortcut for it: negative indexes, which count from the end. Index -1 is the last element, -2 the second to last, and so on:

print(students[-1])
print(students[-2])

This prints:

Ava
David

students[-1] is always the last element, however long the list is. That's why Python programmers write it instead of students[len(students) - 1].

Instructions

Print the number of colleagues with a label: print("Colleagues:", len(colleagues)). The output should be Colleagues: 3.

Create a variable last_colleague and store the last element of colleagues in it. Use a negative index, not the number 2.

Print last_colleague.

Start programming for free

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

Or sign up with:

5/12