🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#functional#map-filter

Functional Programming in Python

map() — apply function to every item:

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]

# Prefer list comprehension:
squares = [x**2 for x in numbers]

filter() — keep items matching condition:

evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]

# Prefer:
evens = [x for x in numbers if x % 2 == 0]

reduce() — aggregate to single value:

from functools import reduce
total = reduce(lambda a, b: a + b, numbers)  # 15
# Prefer: sum(numbers)

functools.lru_cache — memoization:

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

fibonacci(100)  # instant, not exponential

partial — pre-fill function arguments:

from functools import partial
double = partial(lambda x, n: x * n, n=2)
double(5)  # 10

YouTube • Top 10
Python Programming: Functional Programming Tools
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: Functional Programming Tools
Tap to View ›

Reference:

Wikipedia: Functional Programming

image for linkhttps://en.wikipedia.org/wiki/Functional_programming

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT