🎓 A1Learner
🔍

Python Functional Patterns

A functional pattern does a whole-sequence job in one expression.

map versus comprehension

map applies a function to each item. The comprehension does the same job more directly.

nums = [1, 2, 3, 4]
print(list(map(lambda x: x * 2, nums)))
print([x * 2 for x in nums])

filter versus comprehension

filter keeps items where the function returns true. The if in a comprehension reads plainer.

print(list(filter(lambda x: x % 2 == 0, nums)))
print([x for x in nums if x % 2 == 0])

Sort with itemgetter

itemgetter(1) picks the second item of each row. It is a clean key for tuple rows.

from operator import itemgetter

rows = [("Ada", 88), ("Bob", 95), ("Cy", 72)]
print(sorted(rows, key=itemgetter(1), reverse=True))

any and all as quantifiers

any asks if at least one item passes. all asks if every single item passes.

print(any(score >= 90 for score in [88, 95, 72]))
print(all(score >= 60 for score in [88, 95, 72]))

Pair with zip and strict

zip pairs items from two sequences. strict=True promises both sequences have equal length.

print(list(zip(["Ada", "Bob"], [88, 95], strict=True)))

When strict catches a mismatch

Unequal lengths now raise an error at once. Without strict, zip would quietly stop early.

try:
    list(zip(["Ada", "Bob"], [88], strict=True))
except ValueError as e:
    print("ValueError:", e)

Number items with enumerate

The start value sets the first number. Use start=1 for human friendly numbering.

for i, name in enumerate(["Ada", "Bob"], start=1):
    print(i, name)

Example

products = [("  Pen ", 2.5), ("Notebook", 12.0), (" mug", 7.5), ("Desk Lamp", 25.0)]
cleaned = list(map(lambda p: (p[0].strip().lower(), p[1]), products))
cheap = list(filter(lambda p: p[1] < 10, cleaned))
ranked_map = sorted(cheap, key=lambda p: p[1], reverse=True)
ranked_comp = sorted(
    [(name.strip().lower(), price) for name, price in products if price < 10],
    key=lambda p: p[1], reverse=True)
print(ranked_map)
print(ranked_comp)
print("Same result:", ranked_map == ranked_comp)

Key points

  • Quantifier: a check that asks if any item, or every item, passes a test
  • Use map to apply a function to every item in a sequence
  • Use filter to keep only the items where a function returns true
  • Use itemgetter(n) as a fast key that picks item n from each row
  • Use strict=True with zip to raise an error when lengths differ
  • A comprehension usually beats map and filter in Python
  • One expression can do a job over a whole sequence.

In this example, products holds names with messy spaces and prices. The map call cleans each name with strip and lower. The filter call keeps only prices below 10. The sorted call ranks the survivors by price, highest first. The comprehension version does the cleaning and filtering in one expression. Its sorted call then ranks the same short list. Both prints show the same ranked pairs. The last line proves the two routes agree. The comprehension route is the pythonic pick here. It needs no lambda for the cleaning or filtering steps.

Note

It shows the value and the filter in one place, with no lambda needed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which line checks that every score in scores is at least 50?