Variables in Python
Names bind to objects at assignment time. Python is dynamically typed; names don’t carry types—objects do.
Assignment and multiple assignment
Parallel assignment and unpacking keep code concise; swaps need no temp variable.
x = 1
x, y = 10, 20
x, y = y, x
first, *rest = [1,2,3,4]
head, *_, tail = [1,2,3,4] # ignore middle
Mutability and identity
Assignment binds names; lists and dicts are mutable, tuples and strings are immutable.
a = [1, 2]
b = a # b references the same list
b.append(3)
# a is now [1, 2, 3]
Copy when you need independence:
import copy
b = a.copy() # shallow copy
c = copy.deepcopy(a) # deep copy
Scope (LEGB)
Resolution order: Local, Enclosing, Global, Built‑in.
g = 0
def outer():
x = 1
def inner():
nonlocal x
x += 1
inner()
return x
- Use
globalsparingly to assign to module‑level names - Use
nonlocalto write to an enclosing function’s variable
Naming
- snake_case for variables/functions, CapWords for classes
- UPPER_CASE for constants by convention
- Avoid shadowing built‑ins like
list,dict,str
Annotations (optional)
Type hints document intent and enable tooling.
count: int = 0
from typing import List
names: List[str] = ["Ada", "Guido"]
Summary
- Assignment binds names; unpacking/swap are idiomatic
- Understand mutability and LEGB to avoid surprises
- Use annotations for clarity and better tooling