Day 11: List Comprehensions & Lambda Functions

🐍 Day 11: List Comprehensions & Lambda Functions


1. Learning Objectives

By the end of Day 11, you will be able to:

  • Write list comprehensions to create lists in a single, readable line
  • Apply dictionary and set comprehensions for other collection types
  • Use lambda functions for quick, throwaway operations
  • Understand when to use comprehensions vs. traditional loops
  • Recognize the map(), filter(), and reduce() functional tools
  • Know that Python's way is often more readable than classic functional programming

2. Concept Explanation

2.1 Why List Comprehensions? — Power in One Line

Python's list comprehensions let you transform, filter, and create lists in a single, elegant expression. They often replace several lines of loop code, making your intent crystal clear.

Traditional loop vs. comprehension:

# Traditional loop: create a list of squares
squares = []
for x in range(10):
    squares.append(x ** 2)

# List comprehension: same result
squares = [x ** 2 for x in range(10)]

Both produce [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]. The comprehension is shorter, faster, and immediately shows what the list contains.


2.2 List Comprehension Syntax

[expression for item in iterable if condition]
  • expression: What to compute for each item (can use the item).
  • for item in iterable: Loops over the iterable (list, range, string, etc.).
  • if condition (optional): Filters items; only those satisfying the condition are included.

Examples:

# Squares of even numbers 0-9
[x**2 for x in range(10) if x % 2 == 0]   # [0, 4, 16, 36, 64]

# Convert strings to uppercase
names = ["alice", "bob", "charlie"]
uppers = [name.upper() for name in names]   # ['ALICE', 'BOB', 'CHARLIE']

# Extract first letter of each word
firsts = [word[0] for word in ["Python", "Is", "Fun"]]  # ['P', 'I', 'F']

Nested loops in comprehensions (use carefully):

# All combinations of two lists
colors = ["red", "green"]
sizes = ["S", "M"]
combos = [(c, s) for c in colors for s in sizes]
# [('red', 'S'), ('red', 'M'), ('green', 'S'), ('green', 'M')]

2.3 Dictionary & Set Comprehensions

Dictionary comprehension:

{key_expr: value_expr for item in iterable if condition}
# Square numbers: number → square
square_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Swap keys and values
original = {"a": 1, "b": 2}
swapped = {v: k for k, v in original.items()}   # {1: 'a', 2: 'b'}

Set comprehension:

{expression for item in iterable if condition}
# Unique lengths of words
words = ["apple", "banana", "cherry", "date"]
lengths = {len(word) for word in words}   # {5, 6, 4}  (duplicates removed)

# All vowels in a sentence
sentence = "hello world"
vowels = {char for char in sentence if char in "aeiou"}  # {'e', 'o'}

2.4 Lambda Functions — Anonymous Functions

A lambda is a small, anonymous function defined with the lambda keyword. It can have any number of arguments but only one expression (which is implicitly returned).

lambda arguments: expression
# Regular function
def add(x, y):
    return x + y

# Equivalent lambda
add = lambda x, y: x + y
print(add(3, 5))   # 8

Common use cases:

  • As a short callback for functions like sorted(), map(), filter().
  • When you need a simple operation inline without naming a function.
# Sorting a list of tuples by the second element
pairs = [(1, 3), (2, 1), (4, 2)]
pairs.sort(key=lambda pair: pair[1])
print(pairs)  # [(2, 1), (4, 2), (1, 3)]

Caution: Lambdas are limited. If the logic spans multiple lines or is complex, define a regular def function for readability. Use lambdas for tiny, immediate tasks.


2.5 Functional Tools: map(), filter(), reduce()

Python supports classic functional programming functions. However, comprehensions are often more Pythonic and readable.

map(function, iterable) – Apply a function to every item

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))   # [1, 4, 9, 16]

# Better with comprehension:
squared = [x**2 for x in nums]

filter(function, iterable) – Keep items where function returns True

nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))   # [2, 4, 6]

# Better with comprehension:
even = [x for x in nums if x % 2 == 0]

reduce(function, iterable) – Combine items cumulatively

from functools import reduce

nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)   # 24  (1*2*3*4)

# Often clearer with a built-in function or loop:
# import math; math.prod(nums)  (Python 3.8+)

Rule of thumb: Prefer list comprehensions over map()/filter() for clarity. Use reduce() when you genuinely need a cumulative operation, but check if there's a built-in (sum(), any(), all(), etc.).


2.6 When to Use What

Use CaseBest Tool
Create a new list by transforming each itemList comprehension
Filter a list based on a conditionList comprehension with if
Create a dictionary from an iterableDict comprehension
Create a set of unique values from an iterableSet comprehension
Quick one-liner function for sorting, callbacksLambda
Complex transformation, multi-step logicRegular def function

3. Code Examples

Example 1: Filtering and Transforming Data

# All squares of odd numbers from 0-19
odd_squares = [x**2 for x in range(20) if x % 2 == 1]
print(odd_squares)
# [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

Example 2: Nested Comprehension for Flattening

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)   # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 3: Word Length Dictionary

words = ["Data", "Science", "Python", "AI"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
# {'Data': 4, 'Science': 7, 'Python': 6, 'AI': 2}

Example 4: Lambda with sorted()

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78}
]
# Sort by score descending
sorted_students = sorted(students, key=lambda s: s["score"], reverse=True)
for s in sorted_students:
    print(s)

Example 5: Cleaner Code with Comprehensions

# Instead of:
squares = []
for x in range(10):
    if x % 2 == 0:
        squares.append(x**2)

# Use:
squares = [x**2 for x in range(10) if x % 2 == 0]

4. Hands-On Exercises

Exercise 1: Simple List Comprehension

Create a list of the squares of numbers from 1 to 20 (inclusive) using a list comprehension. Print it.

Exercise 2: Filtering with Comprehension

Given the list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], produce a new list containing only the even numbers using a list comprehension.

Exercise 3: Dictionary Comprehension

From the list fruits = ["apple", "banana", "cherry", "date"], create a dictionary where the key is the fruit name and the value is the length of the fruit name, using a dictionary comprehension.

Exercise 4: Set Comprehension

Given a sentence (string), create a set of all unique characters that are vowels (a, e, i, o, u) using a set comprehension. Ignore case.

Exercise 5: Lambda and Sorting

Given a list of tuples prices = [("apple", 0.99), ("banana", 0.25), ("cherry", 1.50)], sort the list by price (second element) using sorted() and a lambda function. Print the sorted list.


5. Applied Challenge Task 🏗️

Data Transformer Pipeline

Build a program that processes a list of employee dictionaries and produces various reports using comprehensions and lambdas.

Given data:

employees = [
    {"name": "Alice", "department": "Engineering", "salary": 75000},
    {"name": "Bob", "department": "Sales", "salary": 50000},
    {"name": "Charlie", "department": "Engineering", "salary": 82000},
    {"name": "David", "department": "Marketing", "salary": 48000},
    {"name": "Eve", "department": "Sales", "salary": 55000},
]

Tasks:

  1. Use a list comprehension to create a list of names of all employees earning more than $60,000.
  2. Use a dictionary comprehension to create a mapping {name: salary} for employees in the "Engineering" department.
  3. Use a set comprehension to find all unique departments.
  4. Use sorted() with a lambda to sort the employees by salary in descending order, then print their names and salaries.
  5. (Stretch) Use reduce() to compute the total payroll (sum of all salaries) – but also check if you can do it with sum().

Output example:

High earners: ['Alice', 'Charlie']
Engineering: {'Alice': 75000, 'Charlie': 82000}
Departments: {'Engineering', 'Sales', 'Marketing'}
Sorted by salary:
  Charlie: $82000
  Alice: $75000
  Eve: $55000
  Bob: $50000
  David: $48000
Total payroll: $310000

6. Brief Review Summary

ConceptKey Points
List comprehension[expr for item in iterable if cond] – concise, readable
Dict comprehension{key: value for item in iterable if cond}
Set comprehension{expr for item in iterable if cond}
Lambdalambda args: expr – tiny anonymous function, one expression only
map() / filter()Functional tools, but comprehensions are often more Pythonic
reduce()Cumulative operation; use functools.reduce
GuidelinePrefer comprehensions for simple transforms and filters; use def for complex logic

7. Preview of Next Topic — Day 12

Tomorrow we organize code like a professional:

  • Modules – splitting code into separate .py files
  • Packages – directories of modules with __init__.py
  • Import statementsimport, from ... import, aliases
  • Virtual environments – isolating project dependencies with venv
  • The if __name__ == "__main__" guard

🎯 Your Action Items for Day 11:

  1. ✅ Complete all 5 exercises
  2. ✅ Build the Data Transformer Pipeline challenge
  3. ✅ Convert some of your old for loops to comprehensions where appropriate
  4. ✅ Practice using lambda with sorted(), max(), min() with custom keys

Comments

Popular posts from this blog

Day 1: Welcome to Python — Your Journey Begins

Python: Your Gateway to Coding Adventures

Earn From the Comfort of Your Home

Build the skills to work comfortably from home, on your own terms.

Get Started Today