Python List Methods
tray starts as rice, then soup. append("bread") puts bread on the end. rice and soup stay in front, in the same order. append does not insert at the front.
print writes the whole tray, brackets and all. bread is last because it was added last.
tray = ["rice", "soup"]
tray.append("bread")
print(tray)
The screen shows rice, soup, and bread, with bread last. The tray now has three values. The new place is 2, and the value there is bread.
pop() takes the last value off. The call is that value, so you can print it. What remains is whatever was already in front. The order of those values does not change.
tray = ["rice", "soup", "bread"]
last = tray.pop()
print(last)
print(tray)
The screen shows bread, then rice and soup. bread is no longer in the tray. last holds bread because that is what pop() just took off.
Each append adds to the end as it is at that moment. Start with rice, append soup, then append bread. The length becomes 3, and place 2 is bread.
tray = ["rice"]
tray.append("soup")
tray.append("bread")
print(len(tray))
print(tray[2])
The screen shows 3, then bread. soup was the end for a moment, then bread became the end. len(tray) counts what is there after both adds.
append grows the end. pop shortens it from the end, and the call is the value that left.
📊 Add or take off
| Action | What changes |
|---|---|
| append | one value is added at the end |
| pop | the last value comes off, and the call is that value |
Two ways this goes wrong
append("bread") never puts bread in front of rice. The end is the only place it adds. pop() on a tray with no values stops the program, because there is no last value to take off. That empty case is not shown above.
The next page changes a value that is already in the list. This page only adds at the end and takes the last value off.
After the change
- What does the first program write, from first value to last?
- What does print(last) write in the second program?
- After that pop, what values are still in the tray?
- What does the third program write, first and then?
Added, then taken off
append("bread") puts bread at the end of rice and soup, so the first screen ends with bread. pop() takes that bread off, print(last) writes bread, and the tray is rice, then soup again. Two appends make the length 3, and place 2 is bread. pop() on an empty tray stops the program.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top