python · level 1 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every item in a list has an , starting at 0.
Picture a queue at an ice cream van. Python numbers each place in the queue, but it starts at 0, not 1. That number is the index. queue[0] is the person at the front.
Negative numbers count from the back, so queue[-1] is the last person. To swap someone, use = with an index: queue[1] = "Dev" puts Dev in place 1.
To add someone, them: queue.append("Eli") puts Eli on the end. queue.remove("Ava") takes Ava out, wherever she is, and everyone behind her moves up.
queue = ["Ava", "Ben", "Cleo"]
print(queue[0], queue[-1])
queue[1] = "Dev"
queue.append("Eli")
queue.remove("Ava")
print(queue) Ask for an index the list does not have, like queue[7], and you get an IndexError.
guess first
Which planet comes out?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
planets = ["Mercury", "Venus", "Earth"]
print(planets[1])
your turn
Your turn. Change the team.
Swap the first player for a name you choose, and add one more name on the end. Then press run.
fix it
This should print the last cake, lemon. Can you fix it?
- Read the last line of the error: IndexError. There is no item at that position.
- Three items have the index numbers 0, 1 and 2. There is no 3.
- Change cakes[3] to cakes[2], or use cakes[-1] for the last item.
nailed it
you can find and change any item. :D
- The first item is at index 0.
[-1]gives you the last item..append()adds to the end..remove()takes an item out.
new words in your collection
- index
- append
This lesson isn’t saved. A free account remembers every lesson you finish.