Functional Programming #
Filter #
Filters elements of a sequence based on a function that returns True
or False
.
# Example: Filtering even numbers from a list
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]
The list
around filter is there so we don’t have to deal with generators, which is one of the more advanced topics in Python.
Map #
Applies a function to every item in a sequence.
# Example: Squaring each number in a list
numbers = [1, 2, 3, 4]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16]
Reduce #
Reduces a sequence to a single value using a function.
from functools import reduce
# Example: Finding the product of a list of numbers
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
List Comprehension #
A compact way to generate or transform lists. Example: Creating a list of squares:
numbers = [1, 2, 3, 4]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16]
Example: Filtering even numbers:
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4]
List comprehension can be used to generate sets and dictionaries.
Lambda Function #
Anonymous, single-expression functions. Handy if you know the function will be short and will not be reused.
# Example: Lambda function to add two numbers
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
# Example: Using lambda with map
numbers = [1, 2, 3, 4]
cubed_numbers = list(map(lambda x: x**3, numbers))
print(cubed_numbers) # Output: [1, 8, 27, 64]