Getting items from a list: positions start at zero
A list keeps its items in order. That means each one has a spot, and you can ask for the item in any spot by its number.
The big idea
Put a position in square brackets after a list's name to get one item. Positions start at 0, so the first item is at 0.
See it in code
The number in the brackets is the position. The first item sits at position 0, the second at 1, and so on:
menu = ["brownie", "cookie", "muffin", "croissant"]
print("First on the menu:", menu[0])
print("Third on the menu:", menu[2])First on the menu: brownie Third on the menu: muffin
The third item is at position 2, not 3. Counting from zero feels odd at first. It soon becomes a habit.
A negative position counts from the end. -1 is always the last item, however long the list gets:
menu = ["brownie", "cookie", "muffin", "croissant"]
print("Today's special:", menu[0])
print("Newest bake:", menu[-1])Today's special: brownie Newest bake: croissant
Add a fifth bake and menu[-1] finds it, with no change to the code. That's the handy part of counting from the back.
Customers count from 1, but the list counts from 0. So when a customer picks a number, take one away to get the position:
menu = ["brownie", "cookie", "muffin", "croissant"]
for spot in range(len(menu)):
print(f"{spot + 1}. {menu[spot]}")
pick = int(input("Pick a number: "))
print("Coming right up:", menu[pick - 1])1. brownie 2. cookie 3. muffin 4. croissant Pick a number: 2 Coming right up: cookie
The customer typed 2. Position 2 - 1 is 1, and position 1 holds cookie, the second bake on the board.
Positions matter anywhere order matters. In the paint studio, palette[0] is the first color in your list. In a game of Snake, position 0 is the snake's head.
Try it yourself
Change menu[2] to menu[3] in the first program and run it. Now try menu[4]. Read the red message. What is Python telling you about your list?
The common mistake
Asking for a position the list doesn't have. A list of four items has positions 0 to 3. Ask for menu[4] and Python stops with an IndexError. The last position is always one less than len(menu).
What it unlocks
Positions pair perfectly with range(), which can count through every spot. To put new items in or take old ones out, see changing lists.