Learn Python

Readable general-purpose language for scripting, data, automation and the web

45 lessons · 9 hours · 4 levels · covers Python 3.13

Python is a high-level, dynamically typed language known for readable syntax and a huge standard library and package ecosystem. It is used for automation, web back ends, data analysis, machine learning, scientific computing and teaching. Learning it pays off quickly: small scripts are easy, and the same language scales to large production systems.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics15 lessons · 2 hours in total
2. PracticalUse it productively at work, with the usual idioms30 lessons · 5 hours in total
3. AdvancedThe less common features, performance and trade-offs39 lessons · 7 hours in total
4. ExpertInternals and the edge cases experts know45 lessons · 9 hours in total

The Python tree

PythonRunning Python: REPL and scriptsRunning Python:REPL and scriptsVariables and built-in typesVariables and built-intypesNumbers and arithmeticNumbers andarithmeticStrings and f-stringsStrings and f-stringsBooleans, comparisons and ifBooleans,comparisons and ifListsListsfor and while loopsfor and while loopsNames, references and mutabilityNames, referencesand mutabilityTuples and unpackingTuples andunpackingDictionariesDictionariesSetsSetsDefining functionsDefining functionsModules and importsModules and importsErrors and try/exceptErrors and try/exceptReading and writing filesReading and writingfilesSlicing sequencesSlicing sequencesComprehensionsComprehensions*args, **kwargs and parameter kinds*args, **kwargs andparameter kindsFunctions as objects, lambdas and closuresFunctions as objects,lambdas and closur…Classes and instancesClasses andinstancesInheritance, super() and compositionInheritance, super()and compositionExceptions in depthExceptions in depthDataclassesDataclassesIterators and generatorsIterators andgeneratorsContext managers and withContext managersand withpathlib for files and directoriespathlib for files anddirectoriescollections and other stdlib gemscollections and otherstdlib gemsVirtual environments and pipVirtual environmentsand pipType hints basicsType hints basicsTesting with pytest and unittestTesting with pytestand unittest
Essentials and Practical shown (30 of 45 lessons); the full list is below. Click a lesson to read it.

All 45 lessons, in order

Basics

  1. Running Python: REPL and scripts · Essentials · 8 min

    Start the interactive interpreter, run a script file, and know which Python you are using.

  2. Variables and built-in types · Essentials · 8 min

    Names point at objects; every object has a type you can inspect with type().

  3. Numbers and arithmetic · Essentials · 8 min

    int, float and the arithmetic operators, including floor division, modulo and powers.

  4. Strings and f-strings · Essentials · 10 min

    Create, combine and format text with str methods and f-strings.

  5. Booleans, comparisons and if · Essentials · 8 min

    Make decisions with if/elif/else, comparison operators, and Python's truthiness rules.

  6. for and while loops · Essentials · 10 min

    Repeat work with for over any iterable, while for conditions, plus break, continue, range and enumerate.

Data structures

  1. Lists · Essentials · 10 min

    The ordered, mutable sequence you'll use most: create, index, change, sort.

  2. Names, references and mutability · Essentials · 10 min

    Assignment never copies: names share objects, and mutable objects change for everyone holding them.

  3. Tuples and unpacking · Essentials · 7 min

    Fixed-size immutable sequences for records, multiple return values and dictionary keys.

  4. Dictionaries · Essentials · 10 min

    Map keys to values for fast lookup; iterate, update and safely read with get().

  5. Sets · Essentials · 6 min

    Unordered collections of unique items with fast membership and set algebra.

  6. Slicing sequences · Practical · 7 min

    Extract, copy, reverse and replace ranges of lists and strings with start:stop:step.

  7. Comprehensions · Practical · 10 min

    Build lists, dicts and sets from iterables in one readable expression.

  8. Structural pattern matching · Advanced · 12 min

    Destructure data by shape with match/case: literals, sequences, mappings, classes and guards.

Functions and iteration

  1. Defining functions · Essentials · 10 min

    Package logic with def, parameters, return values, default arguments and docstrings.

  2. Modules and imports · Essentials · 8 min

    Split code into files and use the standard library with import and from ... import.

  3. *args, **kwargs and parameter kinds · Practical · 12 min

    Variadic arguments, keyword-only and positional-only parameters, and unpacking at call sites.

  4. Functions as objects, lambdas and closures · Practical · 12 min

    Pass functions around, use lambda and key functions, and capture variables in closures.

  5. Iterators and generators · Practical · 12 min

    How for loops really work, and writing lazy sequences with yield.

  6. Decorators · Advanced · 14 min

    Wrap functions to add behaviour, preserve metadata with functools.wraps, and take decorator arguments.

  7. Advanced generators and itertools · Advanced · 12 min

    yield from delegation, generator return values, send/close, and lazy pipelines with itertools.

Errors, files and resources

  1. Errors and try/except · Essentials · 8 min

    Read a traceback, catch the exceptions you expect, and raise your own.

  2. Reading and writing files · Essentials · 10 min

    Open text files with with open(...), read them line by line, and write results back.

  3. Exceptions in depth · Practical · 12 min

    else/finally, custom exception hierarchies, chaining with raise ... from, and exception groups.

  4. Context managers and with · Practical · 10 min

    Guarantee setup and cleanup with the with statement, and write your own with contextlib.

Classes and the object model

  1. Classes and instances · Practical · 12 min

    Define your own types with class, __init__, methods, attributes and a useful __repr__.

  2. Inheritance, super() and composition · Practical · 10 min

    Extend classes with subclasses, call parent logic with super(), and know when to compose instead.

  3. Dataclasses · Practical · 10 min

    Generate __init__, __repr__ and __eq__ for data-holding classes with @dataclass.

  4. Special methods and protocols · Advanced · 14 min

    Make your objects work with ==, hashing, len(), iteration, operators and calls via dunder methods.

  5. Properties and descriptors · Advanced · 14 min

    Computed and validated attributes with @property, and the descriptor protocol behind it.

Standard library

  1. pathlib for files and directories · Practical · 8 min

    Build, inspect and walk file paths portably with pathlib.Path.

  2. collections and other stdlib gems · Practical · 10 min

    Counter, defaultdict, deque and namedtuple, plus when to reach for them.

Environments, typing and testing

  1. Virtual environments and pip · Practical · 10 min

    Isolate each project's dependencies in a venv and install packages with pip.

  2. Type hints basics · Practical · 12 min

    Annotate functions and variables, use built-in generics and unions, and check with a type checker.

  3. Testing with pytest and unittest · Practical · 12 min

    Write automated tests with plain asserts, fixtures and parametrisation, and know unittest.

  4. Generics, Protocols and advanced typing · Advanced · 15 min

    Type-parameter syntax, type aliases, structural Protocols, TypedDict, Literal, overloads and TypeIs.

  5. Packaging with pyproject.toml · Advanced · 14 min

    Lay out a project, declare metadata and dependencies in pyproject.toml, build wheels and publish.

Concurrency

  1. async and await with asyncio · Advanced · 15 min

    Run many I/O-bound tasks concurrently on one thread with coroutines, tasks and TaskGroup.

  2. Threads, processes and concurrent.futures · Advanced · 14 min

    Choose threads for I/O-bound work and processes for CPU-bound work, via executor pools.

CPython internals

  1. The data model: attribute lookup · Expert · 18 min

    Exactly how obj.attr is resolved: __getattribute__, descriptors, instance dicts, __getattr__ and __slots__.

  2. Memory: reference counting and the GC · Expert · 16 min

    How CPython frees objects: reference counts, the cyclic garbage collector, weak references and immortal objects.

  3. The GIL and free-threaded Python · Expert · 16 min

    Why the GIL exists, what it does and doesn't protect, and the experimental free-threaded 3.13 build.

  4. The import system · Expert · 16 min

    sys.modules, finders and loaders, sys.path, bytecode caches, circular imports and lazy module attributes.

  5. Metaclasses and class creation · Expert · 16 min

    How a class statement builds a class via type, and when __init_subclass__ or a metaclass is the right tool.

  6. Bytecode, the interpreter and performance · Expert · 18 min

    Read bytecode with dis, understand the specialising interpreter and JIT, and profile before optimising.