Python Lesson 26: Advanced Python
Congratulations on reaching the final lesson! Here are the advanced Python concepts that will make you a stronger developer: list comprehensions, generators, decorators, and context managers.
List Comprehensions
# Old way (loop)
squares = []
for n in range(10):
squares.append(n ** 2)
# List comprehension (Pythonic)
squares = [n ** 2 for n in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [n for n in range(20) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Transform strings
names = ["alice", "bob", "charlie"]
upper = [name.upper() for name in names]
print(upper) # ['ALICE', 'BOB', 'CHARLIE']
# Dict comprehension
scores = {"Alice":95, "Bob":87, "Charlie":92}
grades = {k: "A" if v>=90 else "B" for k, v in scores.items()}
print(grades)
Generators — Memory Efficient Loops
# Normal function returns all values at once (uses memory)
def make_squares(n):
return [x**2 for x in range(n)]
# Generator yields one at a time (saves memory!)
def gen_squares(n):
for x in range(n):
yield x ** 2 # yields one value, then pauses
# Use a generator
for sq in gen_squares(5):
print(sq) # 0 1 4 9 16
# Generator expression (like list comprehension)
gen = (x**2 for x in range(1000000)) # no memory used yet!
print(next(gen)) # 0 — gets next value on demand
print(next(gen)) # 1
Decorators
import time
# A decorator wraps a function with extra behavior
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs) # call original
end = time.time()
print(f"{func.__name__} took {end-start:.4f}s")
return result
return wrapper
# Apply with @ syntax
@timer
def slow_function():
time.sleep(0.1)
return "done"
result = slow_function()
# slow_function took 0.1001s
Context Managers
# You already know one: with open(...)
with open("file.txt") as f:
data = f.read()
# File closes automatically!
# Create your own context manager
from contextlib import contextmanager
@contextmanager
def timer_ctx(label):
import time
start = time.time()
yield # code inside with block runs here
end = time.time()
print(f"{label}: {end-start:.4f}s")
with timer_ctx("My task"):
# do something that takes time
sum(range(1000000))
# My task: 0.0245s
What to Learn Next
You have completed the Python course!
Next steps on your learning journey:
- Django — Build web applications with Python
- FastAPI — Build APIs and backends
- Pandas + NumPy — Data analysis and science
- JavaScript — Add interactivity to websites
- SQL + Databases — Store and query data
🏋️ Practice Task
Your final challenge: Build one complete project that uses at least 5 concepts from this course (variables, loops, functions, lists, dicts, classes, file I/O, APIs, error handling). Ideas: a stock tracker, a weather dashboard, or a personal expense tracker.
💡 Hint: Plan first: what data do you need? What functions? What classes? Write pseudo-code before writing Python code. Break it into small steps.