8  List Comprehensions and Lambda Functions

8.1 Introduction

This document covers two powerful Python features that help you write more concise and elegant code:

  1. List Comprehension: A compact way to create lists
  2. Lambda Functions: Anonymous functions for simple operations

Both features are fundamental to writing Pythonic code and are widely used in data science, web development, and general programming.


8.2 List Comprehension

What is List Comprehension?

List comprehension provides a concise way to create lists based on existing lists or other iterable objects. Instead of using multiple lines with loops and conditions, you can often accomplish the same task in a single line.

Basic Syntax:

[expression for item in iterable if condition]

8.3 Beginner Level Examples

Example 1: Creating a Simple List

Traditional approach:

# Using a for loop
numbers = []
for i in range(1, 6):
    numbers.append(i)
print("Using for loop:", numbers)
Using for loop: [1, 2, 3, 4, 5]

List comprehension approach:

# Using list comprehension
numbers = [i for i in range(1, 6)]
print("Using list comprehension:", numbers)
Using list comprehension: [1, 2, 3, 4, 5]

Example 2: Squaring Numbers

Traditional approach:

# Squaring numbers with a loop
squares = []
for i in range(1, 6):
    squares.append(i ** 2)
print("Squares using loop:", squares)
Squares using loop: [1, 4, 9, 16, 25]

List comprehension approach:

# Squaring numbers with list comprehension
squares = [i ** 2 for i in range(1, 6)]
print("Squares using comprehension:", squares)
Squares using comprehension: [1, 4, 9, 16, 25]

Example 3: Filtering with Conditions

# Get only even numbers from 1 to 10
even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print("Even numbers:", even_numbers)
Even numbers: [2, 4, 6, 8, 10]

Example 4: String Manipulation

# Convert a list of words to uppercase
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print("Uppercase words:", uppercase_words)
Uppercase words: ['HELLO', 'WORLD', 'PYTHON']

8.4 Intermediate Level Examples

Example 1: Nested List Comprehension

# Create a 3x3 matrix
matrix = [[i + j for j in range(3)] for i in range(0, 9, 3)]
print("Matrix:")
for row in matrix:
    print(row)
Matrix:
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]

Example 2: Flattening a 2D List

# Flatten a 2D list into 1D
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print("Flattened list:", flattened)
Flattened list: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 3: Multiple Conditions

# Numbers divisible by 2 AND 3 (i.e., divisible by 6)
numbers = [num for num in range(1, 31) if num % 2 == 0 if num % 3 == 0]
print("Numbers divisible by both 2 and 3:", numbers)
Numbers divisible by both 2 and 3: [6, 12, 18, 24, 30]

Example 4: If-Else in List Comprehension

# Categorize numbers as even or odd
numbers = range(1, 11)
categorized = ["Even" if num % 2 == 0 else "Odd" for num in numbers]
print("Categorized:", categorized)
Categorized: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

Example 5: Dictionary Comprehension

# Create a dictionary of numbers and their squares
square_dict = {num: num ** 2 for num in range(1, 6)}
print("Square dictionary:", square_dict)
Square dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example 6: Working with Multiple Lists

# Combine two lists using zip
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = [f"{name} is {age} years old" for name, age in zip(names, ages)]
for item in combined:
    print(item)
Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old

8.5 Lambda Functions

What are Lambda Functions?

Lambda functions are small, anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression. They are useful for short, simple operations that you don’t want to formally define with def.

Basic Syntax:

lambda arguments: expression

8.6 Beginner Level Examples

Example 1: Simple Lambda Function

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

print("Regular function:", add(3, 5))

# Lambda equivalent
add_lambda = lambda x, y: x + y
print("Lambda function:", add_lambda(3, 5))
Regular function: 8
Lambda function: 8

Example 2: Single Argument Lambda

# Square a number
square = lambda x: x ** 2
print("Square of 7:", square(7))
Square of 7: 49

Example 3: Lambda with map()

# Double each number in a list
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print("Doubled numbers:", doubled)
Doubled numbers: [2, 4, 6, 8, 10]

Example 4: Lambda with filter()

# Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", evens)
Even numbers: [2, 4, 6, 8, 10]

Example 5: Lambda for String Operations

# Get the length of strings
words = ["apple", "banana", "cherry"]
lengths = list(map(lambda word: len(word), words))
print("Word lengths:", lengths)
Word lengths: [5, 6, 6]

8.7 Intermediate Level Examples

Example 1: Lambda with sorted()

# Sort a list of tuples by the second element
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78), ("Diana", 95)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print("Students sorted by grade:")
for student in sorted_students:
    print(f"{student[0]}: {student[1]}")
Students sorted by grade:
Diana: 95
Bob: 92
Alice: 85
Charlie: 78

Example 2: Lambda with reduce()

from functools import reduce

# Calculate the product of all numbers
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print("Product of all numbers:", product)
Product of all numbers: 120

Example 3: Multiple Lambdas in a Dictionary

# Create a calculator using lambdas
operations = {
    'add': lambda x, y: x + y,
    'subtract': lambda x, y: x - y,
    'multiply': lambda x, y: x * y,
    'divide': lambda x, y: x / y if y != 0 else "Cannot divide by zero"
}

print("10 + 5 =", operations['add'](10, 5))
print("10 - 5 =", operations['subtract'](10, 5))
print("10 * 5 =", operations['multiply'](10, 5))
print("10 / 5 =", operations['divide'](10, 5))
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0

Example 4: Lambda with Conditional Expression

# Categorize numbers as positive, negative, or zero
numbers = [-5, 0, 3, -2, 7, 0, -1]
categories = list(map(lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero", numbers))
print("Categories:", categories)
Categories: ['Negative', 'Zero', 'Positive', 'Negative', 'Positive', 'Zero', 'Negative']

Example 5: Lambda in List Comprehension

# Apply different operations based on condition
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [(lambda x: x ** 2 if x % 2 == 0 else x ** 3)(num) for num in numbers]
print("Squares for even, cubes for odd:", result)
Squares for even, cubes for odd: [1, 4, 27, 16, 125, 36, 343, 64, 729, 100]

Example 6: Nested Lambda Functions

# Create a function that returns a function
multiply_by = lambda x: lambda y: x * y

double = multiply_by(2)
triple = multiply_by(3)

print("Double of 5:", double(5))
print("Triple of 5:", triple(5))
Double of 5: 10
Triple of 5: 15

8.8 Combining List Comprehension and Lambda

Example 1: Filter and Transform

# Get squares of even numbers
numbers = range(1, 11)
even_squares = [num ** 2 for num in numbers if (lambda x: x % 2 == 0)(num)]
print("Squares of even numbers:", even_squares)
Squares of even numbers: [4, 16, 36, 64, 100]

Example 2: Complex Data Processing

# Process a list of products
products = [
    {"name": "Apple", "price": 1.20},
    {"name": "Banana", "price": 0.50},
    {"name": "Orange", "price": 1.50},
    {"name": "Mango", "price": 2.00}
]

# Get names of products priced above $1
expensive = [p["name"] for p in products if (lambda x: x["price"] > 1.0)(p)]
print("Expensive products:", expensive)
Expensive products: ['Apple', 'Orange', 'Mango']

8.9 Example 3: Data Transformation Pipeline

# Transform and filter data in one step
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Square even numbers, cube odd numbers, then filter those greater than 50
result = list(filter(
    lambda x: x > 50,
    map(lambda x: x ** 2 if x % 2 == 0 else x ** 3, data)
))
print("Transformed and filtered:", result)
Transformed and filtered: [125, 343, 64, 729, 100]

8.10 Best Practices

When to Use List Comprehension

✅ DO use when: - Creating a new list from an existing iterable - The operation is simple and readable - You need to filter and transform data

❌ DON’T use when: - The logic is too complex (use regular loops) - You need to perform multiple operations per item - Readability suffers

When to Use Lambda Functions

✅ DO use when: - You need a simple function for a short period - Working with map(), filter(), sorted(), etc. - The function is used only once

❌ DON’T use when: - The function is complex - You need documentation or multiple statements - The function will be reused multiple times (use def instead)


8.11 Practice Exercises

Beginner Exercises

  1. Create a list of numbers from 1 to 20 that are divisible by 3
  2. Convert a list of temperatures in Celsius [0, 10, 20, 30] to Fahrenheit
  3. Write a lambda function that checks if a number is positive

Intermediate Exercises

  1. Create a list of tuples containing numbers and their cubes for numbers 1-10
  2. Sort a list of dictionaries by a specific key using lambda
  3. Use list comprehension to create a list of all vowels from a given string
  4. Implement a lambda function that returns the maximum of three numbers

8.12 Conclusion

List comprehension and lambda functions are powerful tools in Python that help you:

  • Write more concise code
  • Improve code readability (when used appropriately)
  • Think in a more functional programming style
  • Process data efficiently

Remember: Just because you can use these features doesn’t mean you always should. Code clarity should always be your primary concern. Use these tools when they make your code more readable and maintainable, not just to show off!

Further Reading