Python
Python Code Completion Exercises
Complete focused Python snippets as you learn the language.
Interactive exercises that help you practice, check your understanding, and find what to revisit.
Start here
Complete the Python Objects, Values, Types, and Identity Code
Practice reasoning about identity, mutation, equality, and hashability with small Python programs.
Explore the collection
Exercises
Browse the complete collection and choose the resource that matches what you want to practice or understand.
-
ExercisesCore
Complete the Python Objects, Values, Types, and Identity Code
Practice reasoning about identity, mutation, equality, and hashability with small Python programs.
~10 min read Start exercise -
ExercisesBeginner
Complete the Python None code
Practice returning None, checking for None, and distinguishing None from other false values.
~6 min read Start exercise -
ExercisesBeginner
Complete the Python Numbers code
Practice constructing complex numbers, reading their components, combining them with arithmetic, and promoting a real value to complex.
~8 min read Start exercise -
ExercisesBeginner
Complete the Python range code
Practice constructing ascending and descending ranges, testing membership, and slicing range sequences.
~6 min read Start exercise -
ExercisesBeginner
Complete the Python zip code
Practice pairing iterables, enforcing equal lengths, combining several inputs, and unzipping paired data.
~6 min read Start exercise -
ExercisesBeginner
Complete the Python Iterable Unpacking code
Practice exact unpacking, starred targets, nested targets, and value swapping.
~6 min read Start exercise -
ExercisesBeginner
Complete the Python map and filter code
Practice transforming, selecting, combining iterables, and composing map with filter.
~6 min read Start exercise -
ExercisesBeginner
Complete the Python sorting code
Practice sorting iterables, using key functions, ordering multiple fields, and choosing list.sort().
~6 min read Start exercise -
ExercisesBeginner
Complete the Python aggregation code
Practice all(), any(), min(), max(), and sum().
~6 min read Start exercise -
ExercisesBeginner
Complete the Python numeric built-ins code
Practice abs(), divmod(), and pow().
~6 min read Start exercise -
ExercisesIntermediate
Complete the Python recursion code
Practice base cases, recursive steps, and recursive traversal.
~7 min read Start exercise -
ExercisesIntermediate
Complete the Python formatting code
Practice format specifications for width, alignment, numeric precision, and dynamic formatting.
~6 min read Start exercise -
ExercisesIntermediate
Complete the Python coroutine code
Practice defining coroutine functions, awaiting other coroutines, and running an async entry point.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python asynchronous iteration code
Practice implementing and consuming asynchronous iterators with async for, aiter(), and anext().
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python asynchronous generator code
Practice defining asynchronous generators, preserving state across yields, stopping early, and using aclose() or contextlib.aclosing() for deterministic cleanup.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python asynchronous context managers code
Practice implementing __aenter__() and __aexit__(), handling asynchronous cleanup and exception behavior, and using async with.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python enumerations code
Practice defining enum members, looking up a value, iterating over members, and rejecting accidental aliases.
~7 min read Start exercise -
ExercisesIntermediate
Complete the Python object-copying code
Practice making shallow copies, deep copies, preserving recursive structures, and replacing selected record fields.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python deque code
Practice adding and removing items at either end, bounded history, and rotation.
~8 min read Start exercise -
ExercisesBeginner
Complete the Python modules and imports code
Practice importing modules, selecting names, using aliases, and protecting top-level program code.
~7 min read Start exercise -
ExercisesBeginner
Complete the Python tuples and sets code
Practice tuple construction and unpacking, set creation and operations, and immutable set values.
~7 min read Start exercise -
ExercisesAdvanced
Complete Python custom subscription, Sequence, Mapping, and Set code
Practice subscription, assignment, deletion, reverse iteration, and implementing the collections.abc Sequence, Mapping, and Set contracts.
~12 min read Start exercise -
ExercisesIntermediate
Complete the argparse code
Practice typed arguments, option defaults, boolean flags, and subcommands.
~9 min read Start exercise -
ExercisesIntermediate
Complete the asynchronous unittest code
Practise coroutine test methods, awaited exception checks, async cleanup, and await-specific mock assertions.
~10 min read Start exercise -
ExercisesIntermediate
Complete the collections.Counter code
Practice counting iterable items, adding counts, preserving subtracted counts, and intersecting multisets.
~9 min read Start exercise -
ExercisesIntermediate
Complete the collections.defaultdict code
Practice grouping values, collecting unique labels, reading without insertion, and creating independent per-key records.
~8 min read Start exercise -
ExercisesIntermediate
Complete the command-line stream and exit-status code
Practise accessing argument tokens, routing diagnostics, reading standard input, and propagating a command exit status.
~10 min read Start exercise -
ExercisesIntermediate
Complete the dates and times code
Practice date arithmetic, ISO parsing, aware UTC values, and named timezone conversion.
~8 min read Start exercise -
ExercisesIntermediate
Complete the doctest code
Practise writing stable docstring examples, documenting exceptions, distinguishing returned and printed output, and testing examples in text files.
~12 min read Start exercise -
ExercisesIntermediate
Complete the environment configuration code
Practise optional lookups, required settings, numeric validation, and explicit Boolean parsing.
~10 min read Start exercise -
ExercisesIntermediate
Complete the ExitStack code
Practise entering dynamic synchronous and asynchronous resources, registering cleanup callbacks, handling partial acquisition, and transferring cleanup ownership.
~10 min read Start exercise -
ExercisesIntermediate
Complete the filecmp comparison code
Practise byte-accurate comparison, cmpfiles classification, dircmp results, and cache refresh.
~12 min read Start exercise -
ExercisesIntermediate
Complete the filesystem metadata code
Practise querying stat results, interpreting mode bits, inspecting links, and handling expected filesystem errors.
~12 min read Start exercise -
ExercisesIntermediate
Complete the function-caching code
Practice caching deterministic results, limiting stored entries, clearing stale data, and inspecting cache hits.
~8 min read Start exercise -
ExercisesIntermediate
Complete the glob and fnmatch code
Practise rooted pathname matching, lazy recursive search, explicit case-sensitive matching, and literal pattern escaping.
~12 min read Start exercise -
ExercisesIntermediate
Complete the itertools code
Practice flattening, limiting, batching, grouping consecutive records, and building combinations with itertools.
~11 min read Start exercise -
ExercisesIntermediate
Complete the os.scandir() code
Practise scanning directories, filtering DirEntry objects, handling cached status data, and closing iterators safely.
~12 min read Start exercise -
ExercisesIntermediate
Complete the partial-function and method code
Practice pre-filling callable arguments and defining methods with functools.partialmethod while preserving instance binding.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python __init_subclass__ Code
Practice configuring, validating, and registering subclasses with __init_subclass__.
~8 min read Start exercise -
ExercisesAdvanced
Complete the Python __new__ and Object Creation Code
Practice the creation order, subclass-aware __new__(), immutable-value construction, and the boundary where __init__ is skipped.
~8 min read Start exercise -
ExercisesAdvanced
Complete the Python __slots__ Code
Practice declaring slots, restricting attributes, allowing a dictionary explicitly, and using slots across inheritance.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python annotations code
Practice annotated assignment syntax and the compatibility behavior of explicitly stringized annotations.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python argument unpacking code
Practice unpacking iterables and mappings into function calls with * and **.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python assert statements code
Practice writing assertions, attaching diagnostic messages, and choosing explicit exceptions when a check must always run.
~8 min read Start exercise -
ExercisesCore
Complete the Python Assignment Expressions Code
Practice using := to capture values in conditions, loops, and expressions while keeping ordinary assignment separate.
~10 min read Start exercise -
ExercisesCore
Complete the Python Augmented Assignment Code
Practice updating names, mutable objects, attributes, and indexed values with augmented assignment.
~10 min read Start exercise -
ExercisesIntermediate
Complete the Python bisect code
Practise finding left and right insertion points, inserting while preserving order, and maintaining a list of records by key.
~8 min read Start exercise -
ExercisesBeginner
Complete the Python Boolean operators code
Practice using short-circuit and/or expressions to select values, guard access, and avoid unnecessary calls.
~8 min read Start exercise -
ExercisesCore
Complete the Python Bytes and Bytearray Code
Practice constructing bytes, decoding binary data, mutating bytearray, and reading hexadecimal byte values.
~10 min read Start exercise -
ExercisesAdvanced
Complete the Python Callable Object Code
Practice making instances callable with __call__ and using callable-object behavior.
~9 min read Start exercise -
Exercises
Complete the Python Class and Static Methods Code
Practice creating class methods, static methods, and subclass-aware class methods.
~8 min read Start exercise -
ExercisesAdvanced
Complete the Python Class Subscription Code
Practice implementing __class_getitem__ for class subscription and generic-style parameterization.
~9 min read Start exercise -
ExercisesBeginner
Complete the Python classes and objects code
Practice defining a class, initializing instance state, adding methods, and extending a base class.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python comprehensions code
Practice writing list, set, and dictionary comprehensions and using filters.
~8 min read Start exercise -
ExercisesBeginner
Complete the Python conditional expressions code
Practice choosing values with conditional expressions, composing them with larger expressions, and recognizing when the syntax should stay simple.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python context managers code
Practice with statements, implementing context-manager protocols, cleanup, narrow exception suppression, borrowing caller-owned resources with nullcontext(), and closing legacy resources.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python CSV code
Practice reading and writing CSV rows and using dictionary-based CSV access.
~8 min read Start exercise -
ExercisesAdvanced
Complete the Python Custom Attribute Access Code
Practice customizing attribute reads, fallback lookup, assignment, and deletion safely.
~9 min read Start exercise -
ExercisesAdvanced
Complete the Python Custom isinstance() and issubclass() Code
Practice implementing metaclass hooks that customize isinstance() and issubclass().
~10 min read Start exercise -
ExercisesIntermediate
Complete the Python Dataclasses Code
Practice generated class methods, per-instance mutable defaults, post-initialization, and frozen data records.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python decorators code
Practice applying function and class decorators, forwarding wrapper calls, preserving function metadata, configuring factories, and composing decorators.
~10 min read Start exercise -
ExercisesIntermediate
Complete the Python del statements code
Practice deleting name bindings, list targets, slices, and attributes with Python's del statement.
~8 min read Start exercise -
ExercisesAdvanced
Complete the Python Descriptor Code
Practice implementing __get__, __set_name__, __set__, and __delete__ in reusable descriptors.
~9 min read Start exercise -
ExercisesAdvanced
Complete the Python Exception Groups and except* code
Practice creating exception groups and handling their matching subgroups with except*.
~7 min read Start exercise -
ExercisesBeginner
Complete the Python exceptions and error handling code
Practice handling specific exceptions, using else and finally, and deliberately raising an exception.
~7 min read Start exercise -
ExercisesIntermediate
Complete the Python file I/O code
Practice opening, reading, writing, appending, and selecting text or binary file modes.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python function parameters code
Practice positional-only, keyword-only, *args, and **kwargs parameters.
~8 min read Start exercise -
ExercisesAdvanced
Complete the Python generator control code
Practice sending values into a paused generator, handling an injected exception, propagating one, and closing a generator with cleanup.
~10 min read Start exercise -
ExercisesIntermediate
Complete the Python generator expressions code
Practice writing generator expressions and choosing them for lazy iteration.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python generators code
Practice writing generator functions, using yield, and creating generator expressions.
~8 min read Start exercise -
ExercisesAdvanced
Complete the Python generic type parameters code
Practice generic functions, classes, type aliases, and multiple type parameters.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python heapq code
Practice building a heap, adding priorities, removing the smallest item, and using a sequence tie-breaker.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python iterators code
Practice creating and advancing iterators, implementing the iterator protocol, and stopping a callable iterator with a sentinel.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python JSON code
Practice serializing Python data, reading JSON text, and working with JSON files.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python lambda expressions code
Practice writing concise lambda expressions for direct calls, sorting, closures, and predicates.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python logging code
Practice recording events with correct levels, deferred message arguments, exception tracebacks, and formatter configuration.
~9 min read Start exercise -
ExercisesAdvanced
Complete the Python Metaclasses and Class Creation Code
Practice dynamic class creation, metaclass delegation, class-namespace validation, and namespace preparation.
~9 min read Start exercise -
ExercisesAdvanced
Complete the Python Module Attribute Access Code
Practice defining module fallback values, raising AttributeError, exposing dynamic names through dir(), and caching a lazily resolved value.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python Multiple Inheritance and MRO Code
Practice multiple base classes, inspect the MRO, and build a cooperative super() chain.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python operator precedence code
Practice grouping expressions explicitly, applying operator precedence, and reasoning about evaluation order.
~9 min read Start exercise -
ExercisesBeginner
Complete the Python packages and imports code
Practice creating package imports, accessing submodules, and using a relative import inside a package.
~7 min read Start exercise -
ExercisesIntermediate
Complete the Python paths and pathlib code
Practice composing, searching, comparing, normalizing, expanding, splitting, and converting filesystem paths with pathlib and selected os.path functions, including drive/root/tail decomposition, path identity, environment-variable expansion, and str/bytes interoperability.
~18 min read Start exercise -
ExercisesIntermediate
Complete the Python Pattern Matching Code
Practice literal, sequence, mapping, guarded, value, and class match patterns.
~12 min read Start exercise -
Exercises
Complete the Python Properties Code
Practice building managed attributes and using functools.cached_property for reusable per-instance values.
~10 min read Start exercise -
ExercisesIntermediate
Complete the Python regular-expression code
Practice whole-string validation, named groups, lazy match iteration, and readable whitespace normalization.
~10 min read Start exercise -
ExercisesBeginner
Complete the Python scopes and namespaces code
Practice local name resolution, global rebinding, and nonlocal rebinding.
~8 min read Start exercise -
Exercises
Complete the Python Special Methods Code
Practice connecting built-in operations and formatted output to special methods on your own classes.
~10 min read Start exercise -
ExercisesIntermediate
Complete the Python TAR archive code
Practise creating TAR members, reading member bytes, and extracting with an explicit data filter.
~12 min read Start exercise -
ExercisesIntermediate
Complete the Python TOML code
Practice parsing TOML strings and files and handling parsed configuration data.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python type alias statements code
Practice creating type aliases, using aliases in annotations, and inspecting aliased type expressions.
~8 min read Start exercise -
ExercisesIntermediate
Complete the Python Union Types Code
Practice union annotations, None as a union member, supported runtime class checks, and the parameterized-generic runtime boundary.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python unittest code
Practise writing test methods, checking expected exceptions, creating independent fixtures, and using subtests.
~12 min read Start exercise -
ExercisesIntermediate
Complete the Python warnings code
Practice issuing caller-attributed deprecation warnings, defining a warning category, escalating selected warnings, and capturing warnings in a test.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python yield from code
Practice delegating generator output, continuing after delegation, capturing a subgenerator return value, and composing generator layers.
~9 min read Start exercise -
ExercisesIntermediate
Complete the Python ZIP archive code
Practise writing member data, adding filesystem files under portable names, decoding a member, and verifying an archive.
~12 min read Start exercise -
ExercisesIntermediate
Complete the shutil file-operation code
Practise copying files, excluding unwanted tree entries, moving a file, and extracting a tar archive with the data filter.
~10 min read Start exercise -
ExercisesIntermediate
Complete the subprocess code
Practice safe child-process invocation, input/output, nonzero statuses, and timeouts.
~10 min read Start exercise -
ExercisesIntermediate
Complete the temporary-file code
Practise temporary workspaces, file positioning, named-file cleanup, and spooled-storage rollover.
~10 min read Start exercise -
ExercisesIntermediate
Complete the unittest.mock code
Practise controlled return values, sequential outcomes, scoped patching, and autospecced collaborators.
~12 min read Start exercise