0%

Lists · practice

Find Items by Position

A is ordered, so every item has a position. Python calls that position an .

Like indexes, list indexes begin at zero:

Try it

snacks[0] asks for the first item. snacks[1] asks for the second. The brackets after the list name mean “get the item at this index.”

Count backward with negative indexes

A negative index starts from the end:

Try it

Index -1 is the last item, and -2 is the item before it. This is useful when the list length might change and you still want its final item.

An index must exist

A four-item list has indexes 0 through 3. Asking for snacks[4] causes an because there is no fifth item. You do not need to handle that error yet. For now, check the list and use an index that exists.

What does this code print?

levels = ["beginner", "intermediate", "advanced"]
print(levels[0])
print(levels[-1])

Store selected items

An indexed item is a , so you can it to another :

Try it

In the exercise, use the same pattern to select the first and last snacks.

Task

Use indexes to finish the program:

  • Store the first item from snacks in first_snack.

  • Store the last item in last_snack using a negative .

  • Print both selected values, one per line.