Python

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.

  1. 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
  2. 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
  3. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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(" ").
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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.
  19. 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.
  20. 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.
  21. 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.
  22. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. Make a Counter Functions Return a function that remembers a number between calls. The standard introduction to closures and the nonlocal keyword.
  18. Compose Functions Functions Combine several functions into one. A functional-programming staple that tests *args, functions as values and the order of application.
  19. Flatten Nested Lists Functions Flatten lists inside lists of any depth. The classic first recursion problem, with a trap: strings are also iterable.
  20. 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.
  21. 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.
  22. 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.
  23. 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.
  24. 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.
  25. 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.
  26. Temperature with Properties Classes A class with two linked views of one value, validated on every assignment. Properties with getters and setters, done properly.
  27. 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.
  28. 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.
  29. 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.
  30. 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.
  31. 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.
  32. 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.
  33. 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.
  34. 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.
  35. 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.
  36. 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.
  37. 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.
  38. 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.
  39. 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.
  40. 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.
  41. 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.
  42. 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

  1. 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.
  2. 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.
  3. 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.
  4. All Permutations Functions Generate every ordering of a list with recursion. The first backtracking problem, and the one whose base case surprises people.
  5. 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.
  6. 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.
  7. 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.
  8. A Playlist Container Classes Make your own class behave like a list: length, indexing, slicing, looping, membership and addition. The container special methods.
  9. 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.
  10. 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.
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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.