Fundamentals 5 min read

Understanding Python’s map, reduce, filter, and sorted Functions

This article explains how Python’s built‑in higher‑order functions map, reduce, filter, and sorted work, providing clear examples that demonstrate applying functions to iterables, accumulating results, filtering sequences, and customizing sorting with key and reverse options.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Python’s map, reduce, filter, and sorted Functions

The map() function takes a function and an iterable, applying the function to each element and returning a new iterator; for example:

def f(x):
    return x * x
L = map(f, [1,2,3,4,5])
list(L)  # [1, 4, 9, 16, 25]

The reduce() function from functools repeatedly applies a two‑argument function to the items of a sequence, accumulating a single result, e.g.:

from functools import reduce
def fn(x, y):
    return x * 10 + y
reduce(fn, [1,2,3,4,5])  # 12345

Combining map() and reduce() can convert a string of digits to an integer:

from functools import reduce
DIGITS = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(ch):
        return DIGITS[ch]
    return reduce(fn, map(char2num, s))

The filter() function also receives a function and a sequence, keeping elements for which the function returns True . For instance, removing empty strings:

def not_empty(s):
    return s and s.strip()
list(filter(not_empty, ['a', '', 'b', None, '  ']))  # ['a', 'b']

Using filter() together with a generator can produce prime numbers:

def _odd_iter():
    n = 1
    while True:
        n += 2
        yield n

def _not_divisible(n):
    return lambda x: x % n > 0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible(n), it)

for n in primes():
    if n < 1000:
        print(n)
    else:
        break

The built‑in sorted() function returns a new sorted list and can accept a key function and a reverse flag. Examples:

sorted([36, 5, -12, 9, -21])  # [-21, -12, 5, 9, 36]
sorted([36, 5, -12, 9, -21], key=abs)  # [5, 9, -12, -21, 36]
sorted(['bob', 'about', 'Zoo', 'Credit'])  # ['Credit', 'Zoo', 'about', 'bob']
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)  # ['about', 'bob', 'Credit', 'Zoo']
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)  # ['Zoo', 'Credit', 'bob', 'about']
Functional ProgrammingmapreduceFilterbasicssorted
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.