Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Functions

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Functions

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

map passes every item through a function and keeps the count: 1 2 3 4 5 become 1 4 9 16 25; filter is a gate that keeps items unchanged when the test is true: 1 to 8 become 2 4 6 8 map(lambda x: x ** 2, nums) 1 2 3 4 5 machine 1 4 9 16 25 (same count) filter(lambda x: x % 2 == 0, nums) 1 2 3 4 5 6 7 8 gate: yes / no 2 4 6 8 (items unchanged)
map changes every item and keeps the count. filter keeps the items and changes the count.
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

ToolRemember
lambda x: ...one expression, no name; pass it straight in
key=tells sorted, min, max what to compare
mapchanges every item; lazy, read once
filterkeeps items that pass; None means truthy
packagea folder with __init__.py; dots are folders and files
venv + pipcreate, 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 14 of 48

Previous
Type Hints on Python Functions: Parameters, Returns, None and Collections
Next post
Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package

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.

On this page

  • From def to lambda
  • Sorting with a key
  • min and max with a key
  • lambda or def?
  • map: a conveyor belt
  • Why we wrap map in list
  • filter: a gate
  • Modules and packages
  • Two import errors
  • pip and a virtual environment
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.