Python Practice
Practise Python from easy to advanced with interview-style problems, solved in guided steps and tested in your browser. Filter by topic, and grow from the basics to expert level.
3 chapters
82 problems
Start practising →
Course map
3 chapters in order. Start at the first, or jump to the one you need.
- Chapter 1 Easy: Warm-Ups Short problems that each check one idea: conditions, strings, lists, dictionaries and the first traps. Do these first. 22 problems
- Chapter 2 Medium: Interview Core The problems interviewers really ask: sorting with keys, generators, classes, error handling, hashing and your first speed-ups. 42 problems
- Chapter 3 Hard: Advanced Interview Harder designs and speed-ups: caches, descriptors, dynamic programming, binary search, in-place changes and generators that manage state. 18 problems
1. Easy: Warm-Ups
- Leap Year Python Basics Decide whether a year is a leap year. A small problem about the order of exceptions: the most specific rule has to win.
- FizzBuzz Python Basics The famous warm-up question. It is short, so interviewers use it to see whether you notice that one check must come before another.
- Truthy or Falsy Python Basics Count the values in a list that Python treats as true. A question about truthiness, which every Python interview eventually asks.
- Digit Sum Python Basics Add up the digits of an integer, including negative ones. A question about how // and % behave with negative numbers, which surprises many people.
- Reverse the Words Strings Reverse the order of the words in a sentence with messy spacing. A warm-up on split, join and the difference between split() and split(" ").
- Run-Length Encoding Strings Compress a string by replacing each run of the same character with the character and its count. A classic that tests looping, the end of the loop and itertools.groupby.
- Rotate a List Lists and Sorting Rotate a list to the left by k places, where k can be larger than the list, negative or zero. A slicing problem whose real lesson is the modulo operator.
- Split into Chunks Lists and Sorting Split a list into pieces of a given size. Practise slicing with a step in range(), what happens when a slice goes past the end, and raising an error for invalid input.
- Word Count Dictionaries and Sets Count how often each word appears in a text. The first dictionary exercise of every Python course, with the details that make it correct: case, punctuation and the get() idiom.
- Compare Two Lists with Sets Dictionaries and Sets Find what two lists have in common and what is unique to each. The set operators &, - and ^ do in one line what takes loops otherwise.
- Sum of Powers Functions Write a function that takes any number of arguments plus a keyword-only option. A short tour of *args, keyword-only parameters and how Python matches arguments.
- Price Lookup Generators and Iterators Build a dictionary from text lines with a dictionary comprehension, skipping the malformed lines. A small, realistic data-cleaning exercise.
- A Point Class Classes Write a small class with special methods: a readable repr, equality, hashing and addition. The dunder methods every class should know.
- Safe parse_int Errors and Files Turn text into an integer without crashing on bad input. try and except done properly: catch the errors you expect, and do not confuse a valid zero with a failure.
- LCM of a List Standard Library Combine a whole list with one operation using functools.reduce and math.gcd. A short exercise in building on the standard library instead of writing loops.
- Team Pairings Standard Library List every possible pair from a group with itertools.combinations. A one-line problem once you know the right tool, and the right tool to know.
- Call Cost Problem Solving Price a phone call from its length in seconds. A short problem with strict rules, to practise reading every sentence and testing the boundaries.
- Last Word Length Problem Solving Find the length of the last word in a sentence with messy spacing. Practise reading what a word is, and the inputs that break a quick first idea.
- Clean Palindrome Problem Solving Decide whether a sentence reads the same backwards once you ignore case and punctuation. Practise turning a vague rule into exact steps.
- Gift Pair Hashing Find the two items whose prices add up to a gift card, first by trying every pair and then with a dictionary. The classic first lesson in turning a search into a lookup.
- First Repeat Hashing Return the first value that shows up for the second time as you read a list left to right. A set remembers what has been seen, which turns a slow search into a quick lookup.
- First Unique Ticket Hashing Find the first ticket number that appears exactly once in a list. Counting with a dictionary replaces counting the same list again and again.
2. Medium: Interview Core
- The Mutable Default Trap Python Basics Fix a function that remembers values between calls. One of the best-known Python traps, and a favourite interview question about how defaults work.
- Copy or Alias Python Basics Copy a list of lists so that changing the copy never changes the original. A question about references, shallow copies and a surprising result of deepcopy.
- Is It Prime? Python Basics Test whether a number is prime, first by trying every divisor, then by stopping at the square root. The classic example of making a loop do far less work.
- Caesar Cipher Strings Shift every letter of a message along the alphabet, wrapping round from z to a. A problem about characters, ord and chr, and the modulo operator with negative numbers.
- Make a Slug Strings Turn a title into a clean URL slug: lower case, words joined by single hyphens. A real task from web development, solvable by hand or with a regular expression.
- Parse a Log Line Strings Pull the fields out of a log line into a dictionary. Everyday text parsing: splitting with a limit, stripping brackets, and a message that may contain spaces and brackets of its own.
- Longest Common Prefix Strings Find the longest start that all words share. A very common interview question that rewards stating the edge cases (empty list, empty word) before coding.
- Format Money Strings Turn an amount in cents into text like "$1,234.50". Practise divmod, f-string formatting and why money should never be stored as a float.
- Merge Sorted Lists Lists and Sorting Merge two sorted lists into one sorted list by walking along both. This is the merge step of merge sort, and a standard two-pointer pattern.
- Sort with a Key Lists and Sorting Sort records by one field descending and another ascending. The sorted function with a key, tuples that compare element by element, and how to reverse just one criterion.
- Remove Duplicates, Keep Order Lists and Sorting Remove the repeated items from a list but keep the first occurrence of each, in the original order. A set alone loses the order: this problem is about dictionaries that remember it.
- Rotate a Matrix Lists and Sorting Rotate a grid 90 degrees clockwise. A classic interview question that becomes a one-liner once you know zip(*rows) and slicing with a negative step.
- Invert a Dictionary Dictionaries and Sets Swap the keys and values of a dictionary when several keys may share a value. A problem about what happens to collisions, and about setdefault.
- Merge Inventories Dictionaries and Sets Add up two stock dictionaries item by item. Practise dictionary merging, and find out where Counter addition quietly drops data.
- Group By Dictionaries and Sets Write a general group_by that takes any key function. A higher-order function problem: functions are values you can pass in.
- Most Common, Ties Broken Dictionaries and Sets Return the k most frequent items with a fixed tie-break. Counter.most_common is easy to use and easy to use wrongly: this problem is about the order it gives for ties.
- Make a Counter Functions Return a function that remembers a number between calls. The standard introduction to closures and the nonlocal keyword.
- Compose Functions Functions Combine several functions into one. A functional-programming staple that tests *args, functions as values and the order of application.
- Flatten Nested Lists Functions Flatten lists inside lists of any depth. The classic first recursion problem, with a trap: strings are also iterable.
- Fibonacci and Memoization Functions Compute Fibonacci numbers with recursion, see why it is hopelessly slow, and fix it by remembering results. The standard introduction to memoization and dynamic programming.
- Pythagorean Triples Generators and Iterators List all triples a, b, c with a squared plus b squared equal to c squared. Write it as a nested comprehension, then notice that one of the three loops is not needed.
- A Fibonacci Generator Generators and Iterators Write a generator that produces Fibonacci numbers forever. The first generator exercise: yield, lazy evaluation and why an infinite sequence is fine.
- Running Total Generators and Iterators Yield the running total of a stream of numbers, one value at a time. A generator that carries state, and a place to meet itertools.accumulate.
- Bank Account Classes Design a class that protects its own data: a read-only balance, validated operations and a history. Encapsulation with properties and exceptions.
- A Stack Class Classes Implement a stack with a class and use it to build behaviour you can test. A first look at designing a small data structure, with the right errors for misuse.
- Temperature with Properties Classes A class with two linked views of one value, validated on every assignment. Properties with getters and setters, done properly.
- Shapes and Inheritance Classes Build a small class hierarchy with a base class, subclasses that override a method and one that extends another. Inheritance, polymorphism and abstract methods.
- Call With Retry Errors and Files Call a function again when it fails, up to a number of attempts, and give up with the last error. Exception handling in a loop, with the details that decide correctness.
- Read Scores from CSV Errors and Files Parse CSV text with a header, quoted names and bad rows, and report which lines were bad. Realistic data reading, and a reason to use the csv module instead of split.
- Order Totals from JSON Errors and Files Parse JSON text, add up what each customer owes and fail clearly on bad input. Nested data, the json module, and turning a low-level error into a meaningful one.
- A Custom Exception Errors and Files Define your own exception class that carries data, and use it. How to design an error type that callers can catch and inspect.
- Count the Calls Decorators and Advanced Write your first decorator: wrap a function so it counts how often it is called, without breaking its name or its arguments. A decorator is a function that returns a function.
- Log the Calls Decorators and Advanced A decorator that prints each call with its arguments. Builds the text from args and kwargs with repr, and shows why return values must be passed on.
- A Task Dataclass Decorators and Advanced Use @dataclass to write a class with ordering, default values and a safe default list. Dataclasses are the modern way to write plain data classes, and have their own traps.
- Moving Average Standard Library Yield the average of the most recent values of a stream. collections.deque with a maximum length keeps a sliding window without any slicing.
- Extract the Prices Standard Library Pull prices such as $3.50 out of free text with a regular expression. The re module, groups, finditer, and why you test a regex on awkward inputs.
- Closest Points to the Origin Standard Library Pick the k points nearest the origin. A heapq or sorted problem where the real work is choosing a sort key and handling ties.
- Can You Spell It? Standard Library Decide whether a word can be built from a bag of letters, using each letter at most as often as it occurs. Counter arithmetic does the whole job.
- Count File Extensions Standard Library Count files by extension with pathlib instead of string splitting. Dotfiles, double extensions and capital letters are what the simple version gets wrong.
- Meetings Overlap Problem Solving Decide whether two meetings clash. A small problem with a classic trap: the check that looks right misses a case, and touching times are not a clash.
- Group Anagrams Hashing Group words that are made of the same letters. The key idea: choose a dictionary key that is the same for every word in a group, so no two words are ever compared.
- Longest Streak Hashing Find the longest run of consecutive days in an unsorted list. A set makes it linear, and the key insight is to start counting only at the beginning of a run.
3. Hard: Advanced Interview
- Move Zeros In Place Lists and Sorting Move all the zeros of a list to the end, keeping the other items in order, by changing the list itself. A problem about the difference between changing an object and rebinding a name.
- Dictionary Diff Dictionaries and Sets Compare an old and a new configuration and report what was added, removed and changed. A real task, and a tour of dictionary key views.
- Write Your Own partial Functions Re-implement functools.partial: freeze some arguments of a function and get a new function. Tests *args and **kwargs on both sides, and closures.
- All Permutations Functions Generate every ordering of a list with recursion. The first backtracking problem, and the one whose base case surprises people.
- Chunk a Stream Generators and Iterators Split any iterable, even a generator that cannot be sliced, into lists of a given size, lazily. A realistic batching task and a test of how well you know iterators.
- A Reusable Countdown Generators and Iterators Write a class that you can loop over more than once. The difference between an iterable and an iterator is one of the most asked Python interview questions.
- Interleave Iterables Generators and Iterators Take one item from each iterable in turn, until all are used up. A round-robin generator that handles iterables of different lengths.
- A Playlist Container Classes Make your own class behave like a list: length, indexing, slicing, looping, membership and addition. The container special methods.
- LRU Cache Classes Implement a least-recently-used cache. One of the most asked design questions: a dictionary that remembers the order of use and evicts the oldest.
- A Temporary Setting Errors and Files Write a context manager that changes a dictionary entry inside a with block and always puts it back. try / finally, contextlib and how with really works.
- Business Days Errors and Files Count the weekdays between two dates, first by walking day by day and then by counting whole weeks. Practise the datetime module, and a speed-up from arithmetic.
- A Retry Decorator Decorators and Advanced A decorator that takes its own argument: three nested functions. The usual stumbling block of decorators, and a favourite advanced interview question.
- Write memoize Decorators and Advanced Build a decorator that caches results by arguments. This is what functools.cache does, and writing it yourself shows how decorators, dictionaries and recursion fit together.
- A Plugin Registry Decorators and Advanced Make subclasses register themselves just by being defined. __init_subclass__ is a clean modern hook that replaces many metaclass tricks.
- A Lazy Property Decorators and Advanced Write a descriptor that computes a value the first time it is read and then remembers it. The descriptor protocol is how property, classmethod and staticmethod work, so this is a real tour of Python internals.
- Ways to Roll a Total Standard Library Count how many ways n dice can add up to a target. Trying every roll with itertools.product is easy and hopeless for many dice; remembering sub-results fixes it.
- Count in Ranges Standard Library Answer many "how many values lie between low and high" questions on a sorted list. Loops are too slow; bisect finds the boundaries by halving.
- Count Subarrays Hashing Count the stretches of a list that add up to a target. Negative numbers rule out a sliding window, and a dictionary of running totals does the job in one pass.