Grabbing Items
Hoppy needs to take the map out of the backpack. But which pocket is it in?
In Python, we use an Index to access items in a list. The strange thing is: Counting starts at 0!
The Index Spell
backpack = ["Map", "Compass", "Snack"] # Get the FIRST item (Index 0) item1 = backpack[0] # "Map" # Get the SECOND item (Index 1) item2 = backpack[1] # "Compass"
Your Mission
1
The Bag
We have created a list items for you.
2
First Item
Print the first item from the list. Remember the index is 0.
3
Third Item
Print the third item from the list. What is its index? (Hint: 2)
Suggested SolutionClick to expandClick to collapse
Use square brackets [] with the index number:
items = ["Sword", "Shield", "Potion", "Key"] print(items[0]) print(items[2])
Advanced TipsWant more? Click to expandClick to collapse
You can use negative numbers to count from the end! -1 is the last item.
print(items[-1]) # Prints "Key"
pymain.py
Loading...
Terminal
Terminal
Ready to run...