Python's elegant shortcut for creating lists. Write powerful one-liners that replace multi-line loops.
What is a List Comprehension?
A concise way to create lists by applying an expression to each item in an iterable, optionally filtering with a condition. They're faster, cleaner, and more Pythonic than traditional for loops.
comprehensions.py
# Traditional loop โ 3 lines
squares = []
for i inrange(5):
squares.append(i ** 2)
print(squares) # [0, 1, 4, 9, 16]# List comprehension โ 1 line!
squares = [i ** 2for i inrange(5)]
print(squares) # [0, 1, 4, 9, 16]# With filtering (if condition)
evens = [x for x inrange(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]# With transformation + filtering
names = ["Alice", "Bob", "Charlie", "Anna"]
a_names = [n.upper() for n in names if n.startswith("A")]
print(a_names) # ['ALICE', 'ANNA']
Syntax:[expression for item in iterable if condition]. The if condition is optional. You can also nest comprehensions, but keep them readable โ if it spans multiple lines, use a regular loop instead.
Knowledge Check โ Module 13
Q1: What does [x*2 for x in range(3)] produce?
Module 14 of 17
Lambda Functions
Anonymous, single-expression functions for concise, functional-style programming.
What is a Lambda?
A lambda is a small anonymous function that can take any number of arguments but has only one expression. It's perfect for short operations you don't want to name with a full def.
lambda.py
# Regular functiondefadd(a, b): return a + b
# Lambda equivalent
add_lambda = lambda a, b: a + b
print(add(5, 3), add_lambda(5, 3)) # 8 8# Lambda with map() โ apply to every item
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
print(doubled) # [2, 4, 6, 8]# Lambda with filter() โ keep matching items
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums) # [2, 4]# Lambda with sorted() โ custom sort key
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
print(sorted_students) # [('Bob',92),('Alice',85),('Charlie',78)]
When to use Lambda: Use lambdas for short, throwaway functions โ especially with map(), filter(), and sorted(). If your function needs multiple lines or complex logic, use a proper def instead.
Module 15 of 17
Modules & Packages
Organize your code and leverage Python's vast ecosystem of pre-built functionality.
What are Modules?
A module is simply a Python file (.py) containing functions, classes, and variables. Modules let you split your code into logical, reusable pieces. Python comes with a Standard Library of modules (like math, datetime, os), and you can install third-party packages via pip.
modules.py
# Import entire moduleimport math
print(math.sqrt(16)) # 4.0print(math.pi) # 3.141592653589793# Import specific functionsfrom datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))
# Import with aliasimport numpy as np
print(np.mean([1, 2, 3, 4])) # 2.5# Create your own module (save as myutils.py)# from myutils import greet
Output
4.0 3.141592653589793 2026-05-22 14:30 2.5
pip โ Python's Package Manager: Use pip install package_name to install third-party packages. Popular ones: requests (HTTP), pandas (data), flask (web), pillow (images).
Module 16 of 17
Classes & Objects (OOP)
Object-Oriented Programming โ model real-world entities with classes and objects.
Core OOP Concepts
Class โ A blueprint for creating objects (like a cookie cutter)
Object โ An instance of a class (like a cookie)
__init__ โ The constructor method, called when an object is created
self โ Refers to the current instance of the class
oop.py
classStudent:
def__init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
self.courses = []
defenroll(self, course):
self.courses.append(course)
print(f"{self.name} enrolled in {course}")
defget_info(self):
returnf"{self.name}, Age {self.age}, Grade {self.grade}"# Create objects (instances)
alice = Student("Alice", 21, "A")
bob = Student("Bob", 22, "B")
alice.enroll("Python")
alice.enroll("Data Science")
print(alice.get_info())
print("Courses:", alice.courses)
Output
Alice enrolled in Python Alice enrolled in Data Science Alice, Age 21, Grade A Courses: ['Python', 'Data Science']
OOP Benefits: Encapsulation (data + methods together), Reusability (create many objects from one class), Inheritance (child classes extend parent classes). OOP shines in large applications.
Final Module
Capstone Project โ To-Do List App
Apply everything you've learned. Build a complete command-line To-Do List application.
Project Requirements
Build a To-Do List app that can: Add tasks, View all tasks, Mark tasks as complete, Delete tasks, and Save/Load tasks from a file. Use functions, lists, dictionaries, file I/O, and exception handling.
todo_app.py
import json, os
classTodoApp:
def__init__(self, filename="tasks.json"):
self.filename = filename
self.tasks = self.load_tasks()
defload_tasks(self):
try:
withopen(self.filename, "r") as f:
return json.load(f)
except:
return []
defsave_tasks(self):
withopen(self.filename, "w") as f:
json.dump(self.tasks, f)
defadd(self, task):
self.tasks.append({"task": task, "done": False})
self.save_tasks()
print(f"Added: {task}")
deflist_tasks(self):
ifnotself.tasks:
print("No tasks yet!")
for i, t inenumerate(self.tasks):
status = "Done"if t["done"] else"Pending"print(f"{i+1}. [{status}] {t['task']}")
defcomplete(self, index):
if0 <= index < len(self.tasks):
self.tasks[index]["done"] = Trueself.save_tasks()
print("Task marked as done!")
app = TodoApp()
app.add("Learn Python")
app.add("Build a project")
app.list_tasks()
Output
Added: Learn Python Added: Build a project 1. [Pending] Learn Python 2. [Pending] Build a project
You've Completed KODO!
From Python basics to building a real application with OOP, file I/O, and exception handling.
You are now ready to build your own Python projects.
Next Steps: Build more projects (calculator, web scraper, API client), explore frameworks (Flask, Django, FastAPI), contribute to open source, and never stop learning.