Python Tutorial: Scope & References
Where variables live and how Python passes data. The stuff that trips up every intermediate programmer.
Where does your variable live?
Why can't a function see variables from outside? Why does modifying a list inside a function change it everywhere? Why does this work but that doesn't?
Scope and references explain all of it. Ten steps.
What you'll learn in this Python scope & references tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Variables inside functions stay inside — Have you ever created a variable inside a function and then tried to use it outside — only to get a NameError?
- global — reach outside the function — Functions can *read* global variables freely. But to *change* them, you must declare `global`:
- The LEGB rule — When Python looks up a variable name, it searches in this order:
- nonlocal — reach into the enclosing function — `nonlocal` is like `global` but for the enclosing function (not the module):
- Mutable vs immutable — the big 'aha' — Here's something that confuses almost every beginner at least once.
- Copying lists — the gotcha — This trips up almost everyone their first time:
- id() — are these the same object? — `id()` returns the memory address of an object. If two variables have the same `id`, they are literally the same object …
- Build a safe list modifier — Final challenge — no starter code.
Python Scope & References concepts covered
- Where does your variable live?