Python lambda, map, filter, Modules and Packages (with pip and venv)
A lambda is a sticky note next to a def recipe card. Sort words and students with key, map as a conveyor belt, filter as a gate, then your own package with __init__.py, two import errors, and pip install into an activated .venv.
What you will learn
- Write a lambda and pass it as key to sorted, min and max
- Transform every item with map and keep some items with filter, and explain why a map object can be read once
- Build a package with __init__.py, import from it, and tell ModuleNotFoundError from ImportError
- Install a third-party package into an activated virtual environment and record it in requirements.txt
Before you start
- Python Functions: Parameters, Return, Scope, *args and **kwargs
Think about two ways of giving an instruction in a kitchen. For a dish you'll make again and again, you write a recipe card: it has a name, steps, and it goes in the box. But sometimes you just stick a small note on the counter: add two spoons of sugar. One short instruction, no name, used right there.
A normal def is the recipe card. A lambda is the sticky note.
From def to lambda
def square(x):
return x ** 2
print(square(5))
square = lambda x: x ** 2
print(square(5))
add = lambda a, b: a + b
print(add(3, 4))
greet = lambda: "Hello!"
print(greet())
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(7))
print(check(10))
25
25
7
Hello!
Odd
Even
The word lambda replaces def, the arguments go before the colon, and the value after the colon comes back on its own, with no return. There's no name in the lambda itself, which is why it's called an anonymous function. It can take several arguments or none, and make a small decision: read check from the middle, "Even" if the remainder is 0, else "Odd".
The limit: a lambda holds one expression, so there's no room for loops or several lines. And storing one in a variable is only to see it working. Usually you pass a lambda straight into another function.
Sorting with a key
words = ["banana", "pie", "apple", "fig"]
print(sorted(words))
print(sorted(words, key=lambda w: len(w)))
print(sorted(words, key=len))
students = [
{"name": "Alice", "grade": 88},
{"name": "Bob", "grade": 72},
{"name": "Charlie", "grade": 95},
]
top = sorted(students,
key=lambda s: s["grade"],
reverse=True)
print(top[0]["name"])
['apple', 'banana', 'fig', 'pie']
['pie', 'fig', 'apple', 'banana']
['pie', 'fig', 'apple', 'banana']
Charlie
sorted has a parameter called key, a function it calls on each item: banana gives 6, pie 3, apple 5, fig 3. It sorts by those numbers but hands back the words. Pie and fig are both 3, so they keep the order they started in. len is already a function, so you can pass it by name with no brackets.
Two dicts can't be ordered on their own, so the key pulls out the grade. reverse=True puts the highest first, and the whole dicts move, so top[0] is Charlie's. The key doesn't change your data; it only tells sorted what to compare.
min and max with a key
products = [
("Laptop", 999),
("Mouse", 25),
("Keyboard", 75),
]
cheapest = min(products, key=lambda p: p[1])
print(cheapest)
priciest = max(products, key=lambda p: p[1])
print(priciest)
('Mouse', 25)
('Laptop', 999)
p[1] is the price. min doesn't sort anything; it walks the list and remembers the smallest, and it gives back the whole tuple, not just the number.
lambda or def?
names = ["Charlie", "Alice", "Bob"]
print(sorted(names, key=lambda n: len(n)))
def categorize(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
else:
return "C"
for score in [95, 84, 61]:
print(score, categorize(score))
['Bob', 'Alice', 'Charlie']
95 A
84 B
61 C
Short and used once, use a lambda. Anything longer, or anything you'd call twice, write a def. A lambda is a value, so you can even keep a few in a list and call each one in a loop.
map: a conveyor belt
nums = [1, 2, 3, 4, 5]
sq = list(map(lambda x: x ** 2, nums))
print(sq)
names = ["alice", "bob", "charlie"]
print(list(map(str.upper, names)))
data = ["10", "20", "30"]
print(list(map(int, data)))
a = [1, 2, 3]
b = [10, 20, 30]
print(list(map(lambda x, y: x + y, a, b)))
[1, 4, 9, 16, 25]
['ALICE', 'BOB', 'CHARLIE']
[10, 20, 30]
[11, 22, 33]
Every item goes through the machine and comes out changed. The machine doesn't have to be a lambda: str.upper and int are already functions. And map can take two belts, one item from each at a time.
Why we wrap map in list
nums = [1, 2, 3]
result = map(lambda x: x * 10, nums)
print(type(result))
print(list(result))
print(list(result))
<class 'map'>
[10, 20, 30]
[]
Calling map doesn't multiply anything yet. A map object waits and makes each item only when asked. list asks for all of them; ask again and the belt has already run out. If you need the values twice, keep them in a list.
filter: a gate
nums = [1, 2, 3, 4, 5, 6, 7, 8]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
ages = [12, 25, 8, 30, 17, 42]
print(list(filter(lambda a: a >= 18, ages)))
items = ["hello", "", "world", "", "!"]
print(list(filter(None, items)))
mixed = [0, 1, "", "hi", None, True, False]
print(list(filter(None, mixed)))
[2, 4, 6, 8]
[25, 30, 42]
['hello', 'world', '!']
[1, 'hi', True]
Every item gets a yes or a no and comes through unchanged. filter(None, ...) means no function, so Python asks each item whether it's truthy: 0, the empty string, None and False drop out. You'll often write both jobs as a comprehension instead.
Modules and packages
As a program grows, one file isn't enough. A single .py file is a module; every file you've written is already one. Put related modules in a folder with a file called __init__.py, and that folder is a package. __init__.py can be empty; this one prints a line so you can see when it runs.
mypackage/
__init__.py print("mypackage is ready")
math_utils.py add(a, b), double(n)
string_utils.py shout(text), whisper(text)
use_package.py
from mypackage import math_utils
from mypackage.string_utils import shout
print(math_utils.add(3, 4))
print(shout("hello"))
mypackage is ready
7
HELLO!
The dots in an import are just folders and files: mypackage.string_utils is the string_utils file inside the mypackage folder. Python finds the package because it sits beside the file you run. __init__.py runs the first time the package is touched, and only once.
Two import errors
import mypackage.geometry
mypackage is ready
Traceback (most recent call last):
File "S02L02_Packages\missing_module.py", line 1, in <module>
import mypackage.geometry
ModuleNotFoundError: No module named 'mypackage.geometry'
from mypackage.math_utils import subtract
mypackage is ready
Traceback (most recent call last):
File "S02L02_Packages\missing_name.py", line 1, in <module>
from mypackage.math_utils import subtract
ImportError: cannot import name 'subtract' from 'mypackage.math_utils' (S02L02_Packages\mypackage\math_utils.py)
"No module named" means check the file and folder. "Cannot import name" means the file is fine, so check what's inside it.
pip and a virtual environment
Thousands of packages other people wrote live on PyPI, and pip installs them. By default it installs into the one Python on your computer, shared by every project, so a project that needs an old version and one that needs a new version collide. A virtual environment gives each project its own toolbox: a folder with its own Python and packages. The order matters: create, then activate, then install.
python -m venv .venv
.venv\Scripts\activate # Windows
source .venv/bin/activate # Mac
where python # top line now points inside .venv
pip install tabulate
Before installing, a small file that imports tabulate fails with ModuleNotFoundError: No module named 'tabulate', because this toolbox is empty. After pip install tabulate, which ends with Successfully installed tabulate-0.10.0, the same file runs:
from tabulate import tabulate
rows = [("Laptop", 999), ("Mouse", 25)]
print(tabulate(rows, headers=["Item", "Price"]))
Item Price
------ -------
Laptop 999
Mouse 25
If you skip activate, pip puts everything into your global Python. To share the setup, pip freeze > requirements.txt writes one line, tabulate==0.10.0, and a teammate runs pip install -r requirements.txt in their own fresh environment. Share the requirements file, not the .venv folder. The full story is in Python virtual environments with venv, and the modern way with uv and pyproject.toml.
Quick recap
| Tool | Remember |
|---|---|
lambda x: ... | one expression, no name; pass it straight in |
key= | tells sorted, min, max what to compare |
map | changes every item; lazy, read once |
filter | keeps items that pass; None means truthy |
| package | a folder with __init__.py; dots are folders and files |
| venv + pip | create, activate, install; share requirements.txt |
Try it yourself
Add a subtract function to math_utils.py and run the failing import again. Or prompt an AI tool to write it, and then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
A function is a recipe: write it once, hand in ingredients, get a dish back. input and import, def and return, defaults, returning a tuple, functions as objects, the LEGB scope rule, global and nonlocal, then *args and **kwargs, with real output.
Type Hints on Python Functions: Parameters, Returns, None and Collections
A type hint is a label on a jar: it says what belongs inside but stops nothing. Hint parameters and returns, -> None, str | None, list[str] and dict[str, int], see add("2", "3") print 23, and read hints back with __annotations__.
Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
Three work-style use cases (an HR bonus calculator, a product discount pipeline, and a mathkit package) turned into requirement lists and prompts, with one possible result for each read against the list, including the empty-input crash the list forgot.
