Lambda Functions

Lambda functions, also known as anonymous functions, are small, one-line functions that can have any number of arguments but can only have a single expression.

square = lambda x: x ** 2
result = square(5)
print(result)  # Output: 25

Map, Filter, Reduce

The map(), filter(), and reduce() functions are part of the functional programming paradigm in Python.

  • map() applies a function to each item in an iterable and returns a map object with the results.
  • filter() creates a new iterable by selecting elements from an existing iterable based on a condition.
  • reduce() applies a function of two arguments cumulatively to the elements of a sequence, from left to right, to reduce the sequence to a single value.
numbers = [1, 2, 3, 4, 5]
map()
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # Output: [1, 4, 9, 16, 25]
filter()
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4]
reduce() (from functools module)
from functools import reduce
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers)  # Output: 15

List Comprehensions

List comprehensions provide a concise way to create new lists by applying an expression to each item in an iterable.

numbers = [1, 2, 3, 4, 5]
List comprehension
squared = [x ** 2 for x in numbers]
print(squared)  # Output: [1, 4, 9, 16, 25]
List comprehension with condition
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)  # Output: [2, 4]

Generator Expressions

Generator expressions are similar to list comprehensions but generate values lazily, one at a time, instead of creating an entire list in memory.

numbers = [1, 2, 3, 4, 5]
Generator expression
squared_generator = (x ** 2 for x in numbers)
print(squared_generator)  # Output:  at 0x7f9b3c8e6c40>
Iterate over the generator
for value in squared_generator:
print(value)
Output: 1, 4, 9, 16, 25

In the next chapter, we'll learn about working with dates and times in Python using the datetime module.