Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.1 — Lists: Ordered, Changeable Collections
Python · Example 1 of 3

Build and change a shopping list

Predict each printed line before you press Run. Then change an index and see the IndexError message in the Break it section.

A list holds many values in a fixed order, and you can add, remove and change items after it is created. Each item has a position number (an index) starting at 0, and a list stores references to its items, not copies of them.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a list scores = [70, 85, 90]. Add 100 at the end, insert 60 at the start, then print the list and its length.

02

Given tasks = ["wash", "cook", "study", "sleep"], remove the last task and print which one you removed, then print the list.

03

Make a = [1, 2] and b = a. Append 3 through b. Print both and print whether they are the same list. Then make a real copy c and show that appending to c does not change a.

Explain it without notes

01

What does it mean that a list is mutable, and how is that different from a string?

02

What is the difference between append and extend?

03

Why does changing b also change a after b = a, and how do you get a real copy?

04

Why is x in my_list slow for big lists, and what would you use instead?

05

Why is append O(1) but insert(0, x) O(n)? Is append always cheap?

Build and change a shopping list
Sign in to run this example in your browser.

Expected output

Start: ['milk', 'eggs', 'bread']
First: milk
Last: bread
Length: 3
After adding: ['milk', 'butter', 'eggs', 'bread', 'rice', 'tea', 'salt']
Popped: salt
After removing: ['milk', 'butter', 'bread', 'rice', 'tea']
Is tea in the cart? True
Is salt in the cart? False
Index of bread: 2