Making Code Faster

The most valuable optimization in everyday programming is replacing a nested search with a dictionary lookup. Checking whether something is in a list is O(n), because it may have to check every item. Checking a dictionary or set is O(1), because it jumps straight there.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Add more names to the list, including new duplicates, and confirm both versions still agree.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ When not to optimize

Correct and readable beats fast and clever, until the data gets big enough to matter. Write the clear version first, measure whether it is actually too slow, and only then reach for a faster structure. Optimizing code nobody is waiting on is wasted effort, and the complicated version is where bugs live.

◈ Graded Challenge

Write a function that returns True when a list contains any duplicate value, and False otherwise. Solve it in a single pass using a set, rather than comparing every pair.

Name it exactly: def has_duplicates(items):

3 visible + 3 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back