5.
List Comprehension with Functions
Example: Converting a list of strings to uppercase
words = ["hello", "world", "python"]
upper_words = [[Link]() for word in words]
print(upper_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
6. List Comprehension with Nested List
Comprehension
Example: Flattening a 2D list
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]
7. List Comprehension with Set and Dictionary
Comprehensions
Set Comprehension
unique_numbers = {x for x in [1, 2, 2, 3, 4, 4]}
print(unique_numbers) # Output: {1, 2, 3, 4}
Dictionary Comprehension
squared_dict = {x: x**2 for x in range(5)}
print(squared_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
8. When to Use List Comprehensions?
• You need to create a list in a single line
• The logic is simple and readable
• You want to improve performance (faster than loops)
Avoid when: - The logic is too complex (use a standard loop instead for clarity)
9. Performance Comparison: List Comprehension
vs. Loop
import time
# Using a for loop
start = [Link]()
squares_loop = []
for x in range(10**6):
squares_loop.append(x**2)
print("Loop time:", [Link]() - start)
# Using list comprehension
start = [Link]()
squares_comp = [x**2 for x in range(10**6)]
print("List Comprehension time:", [Link]() - start)
List comprehensions are generally faster than loops because they are optimized
internally by Python.
Summary
Concept Example
Basic List Comprehension [x**2 for x in range(5)]
[x for x in range(10) if x % 2 ==
With Condition ( if )
0]
["Even" if x % 2 == 0 else "Odd"
With if-else
for x in range(5)]
[(x, y) for x in range(2) for y
Nested Loop
in range(3)]
[num for row in matrix for num in
Flatten 2D List
row]
Set Comprehension {x for x in [1, 2, 2, 3]}
Dictionary Comprehension {x: x**2 for x in range(5)}
Lambda Functions
A lambda function in Python is an anonymous, single-expression function
defined using the lambda keyword. It is commonly used for short, throwaway
functions where a full function definition is unnecessary.
1. Syntax of Lambda Functions
lambda arguments: expression
• lambda → Keyword to define a lambda function
• arguments → Input parameters (comma-separated)
• expression → The operation performed (must be a single expression, not
multiple statements)
Example: Simple Lambda Function
square = lambda x: x ** 2
print(square(5)) # Output: 25
2. Using Lambda Functions with map() , filter() ,
and reduce()
2.1 Using map() with Lambda
Applies a function to each element of an iterable.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
2.2 Using filter() with Lambda
Filters elements based on a condition.
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4, 6]
2.3 Using reduce() with Lambda
Reduces an iterable to a single value (requires [Link] ).
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
3. Lambda with Multiple Arguments
Example: Adding Two Numbers
add = lambda x, y: x + y
print(add(3, 7)) # Output: 10
Example: Finding the Maximum of Two Numbers
maximum = lambda x, y: x if x > y else y
print(maximum(10, 5)) # Output: 10
4. Lambda in Sorting Functions
Sorting a List of Tuples
students = [("Alice", 85), ("Bob", 78), ("Charlie", 92)]
[Link](key=lambda student: student[1]) # Sort by score
print(students) # Output: [('Bob', 78), ('Alice', 85), ('Charlie', 92)]
5. When to Use Lambda Functions?
Use Lambda Functions When:
• The function is short and simple.
• Used temporarily inside another function (e.g., map , filter ).
• Avoiding defining a full function with def .
Avoid Lambda Functions When:
• The function is complex (use def for readability).
• Multiple operations/statements are needed.
Summary
Feature Example
Basic Lambda Function lambda x: x**2
With map() map(lambda x: x**2, numbers)
With filter() filter(lambda x: x % 2 == 0, numbers)
With reduce() reduce(lambda x, y: x * y, numbers)
Multiple Arguments lambda x, y: x + y
Sorting with Lambda sort(key=lambda x: x[1])