loop
Lists and list processing

Module 3 · Lists and list processing · Lesson 2 of 7

Indexing lists

Each value in a list lives at a numbered position — its index. To read one, put its index in square brackets after the list: nums[2]. The catch that trips up every beginner: counting starts at 0, so nums[0] is the first item.

nums = [10, 20, 30, 40]
010-4
120-3
230-2
340-1

Here's a lovely Python convenience: negative indices are legal, and they count from the end. nums[-1] is the last item, nums[-2] the one before it. No need to know the length to grab the final element.

Run it yourselfruns in your browser · Python
main.py

One boundary to respect: an index that doesn't exist — nums[4] on a four-item list — raises an IndexError. (Uncomment the last line and run it to meet one.) Valid indices run from 0 to len(nums) - 1, or -1 down to -len(nums).