Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.11 — Choosing the Right Structure and Its Cost
Python · Example 2 of 2

Same answer, very different work

sys.getsizeof(x) tells you how many bytes the object x takes in memory. The two import lines load ready-made toolboxes (Topic 6.1 teaches import).

Every container makes some operations cheap and others expensive. This topic explains Big-O in plain words, compares the cost of the common operations on lists, deques, sets and dictionaries, and gives a short guide for choosing on purpose.

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

You have emails = [...] with 50,000 items and must test thousands of addresses against it. Show how to set it up for fast tests, using a short example list.

02

Which container would you use for: (a) the last 5 messages of a chat, (b) the number of times each word appears, (c) unique visitor ids? Print your answers as three lines.

03

Write a loop that counts how many steps a linear search takes to find 7 in [3, 9, 7, 1] and print the count.

Explain it without notes

01

What does O(1), O(n) and O(n²) mean, with one Python example of each?

02

Why is x in my_set O(1) but x in my_list O(n)?

03

When would you use a deque instead of a list?

04

How would you speed up a loop that checks if name in names against a list of 100,000 names?

05

How would you find the 3 largest numbers in a list of a million numbers, and what does each approach cost?

Same answer, very different work
Sign in to run this example in your browser.

Expected output

list in list: 500 common items, 1124750 comparisons
with a set: 500 common items, 1000 lookups
same answer: True
set uses more memory than list: True
tuple not bigger than list: True
popleft: 0 | left: [1, 2, 3, 4]