Command Palette

Search for a command to run...

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

append or extend?

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?

append or extend?
Sign in to run this example in your browser.

Expected output

append: [1, 2, [3, 4]] -> length 3
extend: [1, 2, 3, 4] -> length 4
extend with a string: [1, 2, 'h', 'i']