ZetCode

Python funcy

last modified November 30, 2026 Python 3.15

In this article we show how to use the funcy library. Funcy is a collection of small functional tools for working with sequences, dictionaries, and functions. It fills gaps in the standard itertools, functools, and operator modules with ready-made helpers such as distinct, merge_with, or retry.

Most funcy sequence functions come in two flavours. The plain name, for example split, returns a lazy iterator; the name with an l prefix, for example lsplit, returns a list. We use the list versions in most examples so that the results can be printed directly.

The examples were tested with funcy 2.1. The library is installed from PyPI.

$ pip install funcy

Removing duplicates

The distinct function removes duplicate items while keeping the order of first occurrence. A plain set also removes duplicates, but it does not keep the order.

unique_words.py
from funcy import distinct

words = ['sky', 'war', 'water', 'war', 'sky', 'cup', 'cup', 'atom']

print(type(distinct(words)))
print(list(distinct(words)))
print(list(distinct(words, key=len)))

Like most funcy functions without the l prefix, distinct returns a generator, so we turn it into a list before printing it. The optional key function decides when two items count as the same. With key=len, only the first word of each length is kept: sky (3 letters), water (5), and atom (4).

$ python unique_words.py
<class 'generator'>
['sky', 'war', 'water', 'cup', 'atom']
['sky', 'water', 'atom']

Splitting a sequence

Funcy has three ways of cutting a sequence in two. The split function sorts items into two groups by a predicate, split_by cuts the sequence where a predicate first fails, and split_at cuts it at a position.

split_values.py
from funcy import lsplit, lsplit_by, lsplit_at

values = [1, 4, 6, 9, 3, 12, 7, 2]

evens, odds = lsplit(lambda e: e % 2 == 0, values)
print(evens, odds)

small, rest = lsplit_by(lambda e: e < 8, values)
print(small, rest)

head, tail = lsplit_at(5, values)
print(head, tail)

The lsplit call returns the items that pass the test and the items that fail it; each group keeps the original order. The lsplit_by function works like takewhile and dropwhile together: the first part ends at 9, the first value that is not smaller than 8, even though later values such as 3 are small again. The lsplit_at function simply cuts after the fifth item.

$ python split_values.py
[4, 6, 12, 2] [1, 9, 3, 7]
[1, 4, 6] [9, 3, 12, 7, 2]
[1, 4, 6, 9, 3] [12, 7, 2]

Chunks and sliding windows

The chunks function cuts a sequence into pieces of a given size, while partition keeps only complete pieces and can also produce overlapping windows. The pairwise and with_prev functions pair each item with its neighbour.

chunks_parts.py
from funcy import lchunks, lpartition, pairwise, with_prev

temps = [12, 14, 13, 17, 19, 18, 15]

print(lchunks(3, temps))
print(lpartition(3, temps))
print(lpartition(3, 1, temps))

for prev, cur in pairwise(temps):
    print(f'{prev} -> {cur}: {cur - prev:+d}')

print(list(with_prev(temps[:3])))

The last chunk holds only the one remaining temperature; lpartition(3, temps) drops it because it is incomplete. With a step argument, lpartition(3, 1, temps) moves the window by one item at a time, which gives all runs of three consecutive days. The pairwise function yields consecutive pairs, so we can compute the day-to-day change. The with_prev function pairs each item with the previous one and uses None for the first item.

$ python chunks_parts.py
[[12, 14, 13], [17, 19, 18], [15]]
[[12, 14, 13], [17, 19, 18]]
[[12, 14, 13], [14, 13, 17], [13, 17, 19], [17, 19, 18], [19, 18, 15]]
12 -> 14: +2
14 -> 13: -1
13 -> 17: +4
17 -> 19: +2
19 -> 18: -1
18 -> 15: -3
[(12, None), (14, 12), (13, 14)]

Flattening nested sequences

The flatten function walks into nested lists and tuples to any depth, while cat joins just one level of nesting. The mapcat function maps a function over a sequence and joins the resulting sequences.

flatten_lists.py
from funcy import lflatten, lcat, lmapcat

nested = [1, [2, 3], [[4, 5], 6], (7, 8)]
print(lflatten(nested))
print(lflatten(nested, follow=lambda e: isinstance(e, list)))

rows = [[1, 2], [3], [], [4, 5]]
print(lcat(rows))

sentences = ['an old falcon', 'a blue sky']
print(lmapcat(str.split, sentences))

By default, lflatten follows every iterable except strings and bytes. The follow argument decides which items to open; here only lists are flattened, so the tuple stays as it is. The lcat function concatenates the rows, and lmapcat(str.split, sentences) splits each sentence into words and joins all the words into one list.

$ python flatten_lists.py
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, (7, 8)]
[1, 2, 3, 4, 5]
['an', 'old', 'falcon', 'a', 'blue', 'sky']

Extended function semantics

Where funcy expects a function, it also accepts a few other objects. A string is treated as a regular expression, a set as a membership test, and a dictionary as a lookup table. This makes many short lambda functions unnecessary.

extended_semantics.py
from funcy import lmap, lfilter, lremove, lkeep, lpluck

lines = ['id: 12', 'no number', 'id: 7', 'total 120 items']
print(lmap(r'\d+', lines))
print(lkeep(r'\d+', lines))

colours = ['red', 'green', 'blue', 'black', 'white']
print(lfilter({'red', 'blue'}, colours))
print(lremove(r'^b', colours))

codes = {'sk': 'Slovakia', 'hu': 'Hungary', 'pl': 'Poland'}
print(lmap(codes, ['pl', 'sk']))

users = [{'name': 'Alice', 'role': 'admin'},
         {'name': 'Bob', 'role': 'user'},
         {'name': 'Paul', 'role': 'admin'}]
print(lpluck('name', users))

With a regular expression, lmap returns the matched text, or None when there is no match. The lkeep function is a map that drops false results, so it keeps only the numbers. A set passed to lfilter keeps the items that are in the set, and lremove is the opposite of lfilter: it drops the colours that start with b. A dictionary passed to lmap translates keys to values.

Since strings mean regular expressions, a string cannot be used to read a dictionary key. For that, funcy provides pluck, which takes the same key from every dictionary in a sequence.

$ python extended_semantics.py
['12', None, '7', '120']
['12', '7', '120']
['red', 'blue']
['red', 'green', 'white']
['Poland', 'Slovakia']
['Alice', 'Bob', 'Paul']

Transforming dictionaries

The walk_keys and walk_values functions apply a function to all keys or all values of a dictionary. select_keys and select_values filter dictionary entries, and project and omit keep or drop the given keys.

dict_transform.py
from funcy import walk_keys, walk_values, select_keys, select_values
from funcy import project, omit

user = {'Name': 'Alice', 'Email': 'ALICE@EXAMPLE.COM', 'City': 'NeW YoRk',
        'Password': 's3cret'}

print(walk_keys(str.lower, user))
print(walk_values(str.lower, user))

stock = {'apples': 12, 'pears': 0, 'plums': 4, 'peaches': 0}
print(select_values(bool, stock))
print(select_keys(r'^p', stock))

print(project(user, ['Name', 'City']))
print(omit(user, ['Password']))

All these functions return a new dictionary of the same type and leave the original unchanged. Passing bool to select_values keeps the products that are in stock, and the regular expression r'^p' selects keys that start with p. The omit function is handy for removing sensitive fields such as passwords before printing or logging a record.

$ python dict_transform.py
{'name': 'Alice', 'email': 'ALICE@EXAMPLE.COM', 'city': 'NeW YoRk', 'password': 's3cret'}
{'Name': 'alice', 'Email': 'alice@example.com', 'City': 'new york', 'Password': 's3cret'}
{'apples': 12, 'plums': 4}
{'pears': 0, 'plums': 4, 'peaches': 0}
{'Name': 'Alice', 'City': 'NeW YoRk'}
{'Name': 'Alice', 'Email': 'ALICE@EXAMPLE.COM', 'City': 'NeW YoRk'}

Merging dictionaries

The merge function combines dictionaries; for a repeated key the last value wins. The merge_with function collects all values of a repeated key and combines them with a given function.

merge_sales.py
from funcy import merge, merge_with

store1 = {'apples': 120, 'pears': 80}
store2 = {'apples': 150, 'plums': 60}
online = {'pears': 110, 'plums': 90}

print(merge(store1, store2, online))
print(merge_with(sum, store1, store2, online))
print(merge_with(list, store1, store2, online))

defaults = {'host': 'localhost', 'port': 8080, 'debug': False}
config = {'port': 9000}
print(merge(defaults, config))
print(defaults)

With plain merge, the sales of the later stores overwrite the earlier ones. merge_with(sum, ...) adds the values for each product, and merge_with(list, ...) just collects them. Merging a dictionary of defaults with a smaller configuration dictionary is a common way to fill in missing settings; the defaults themselves are not changed.

$ python merge_sales.py
{'apples': 150, 'pears': 110, 'plums': 90}
{'apples': 270, 'pears': 190, 'plums': 150}
{'apples': [120, 150], 'pears': [80, 110], 'plums': [60, 90]}
{'host': 'localhost', 'port': 9000, 'debug': False}
{'host': 'localhost', 'port': 8080, 'debug': False}

Grouping and counting

The group_by function sorts items into lists by a key function, and count_by counts how many items fall into each group.

group_count.py
from funcy import group_by, count_by, count_reps, group_values

users = [
    {'name': 'Alice', 'occupation': 'pilot'},
    {'name': 'Bob', 'occupation': 'driver'},
    {'name': 'Charlie', 'occupation': 'teacher'},
    {'name': 'David', 'occupation': 'teacher'},
    {'name': 'Eva', 'occupation': 'driver'},
    {'name': 'Frank', 'occupation': 'teacher'},
]

by_job = group_by(lambda u: u['occupation'], users)
for job, members in by_job.items():
    print(job, [u['name'] for u in members])

print(dict(count_by(lambda u: u['occupation'], users)))

print(dict(count_reps('mississippi')))

pairs = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'plum')]
print(dict(group_values(pairs)))

Unlike itertools.groupby, funcy's group_by does not need sorted input; it returns a defaultdict that maps each key to a list of items. The count_by function returns a defaultdict of counts, and count_reps counts repeated items directly. The group_values function builds a dictionary of lists from key-value pairs.

$ python group_count.py
pilot ['Alice']
driver ['Bob', 'Eva']
teacher ['Charlie', 'David', 'Frank']
{'pilot': 1, 'driver': 2, 'teacher': 3}
{'m': 1, 'i': 4, 's': 4, 'p': 2}
{'fruit': ['apple', 'plum'], 'veg': ['carrot']}

Nested data

Data loaded from JSON is often deeply nested. The get_in function reads a value by a path of keys and indexes, and set_in, update_in, and del_in return modified copies of the data.

nested_data.py
from funcy import get_in, set_in, update_in, del_in

order = {
    'id': 1021,
    'customer': {'name': 'Alice', 'address': {'city': 'Bratislava'}},
    'items': [{'sku': 'A-1', 'qty': 2}, {'sku': 'B-7', 'qty': 1}],
}

print(get_in(order, ['customer', 'address', 'city']))
print(get_in(order, ['items', 1, 'sku']))
print(get_in(order, ['customer', 'phone'], 'n/a'))

moved = set_in(order, ['customer', 'address', 'city'], 'Kosice')
print(moved['customer'])
print(order['customer'])

more = update_in(order, ['items', 0, 'qty'], lambda q: q + 3)
print(more['items'])

anonymous = del_in(order, ['customer', 'name'])
print(anonymous['customer'])

A path is a list of keys and list indexes. When a key is missing, get_in returns the default value instead of raising KeyError. The other functions copy the dictionaries and lists along the path and leave the original data untouched, as the second printed customer shows. The update_in function computes the new value from the old one.

$ python nested_data.py
Bratislava
B-7
n/a
{'name': 'Alice', 'address': {'city': 'Kosice'}}
{'name': 'Alice', 'address': {'city': 'Bratislava'}}
[{'sku': 'A-1', 'qty': 5}, {'sku': 'B-7', 'qty': 1}]
{'address': {'city': 'Bratislava'}}

Composing functions

The compose function chains functions from right to left, like in mathematics, and rcompose chains them from left to right. The partial and rpartial functions fix some arguments of a function, and juxt calls several functions with the same arguments.

compose_funcs.py
from funcy import compose, rcompose, partial, rpartial, ljuxt

def square(x):
    return x * x

def increment(x):
    return x + 1

f = compose(square, increment)
g = rcompose(square, increment)
print(f(5), square(increment(5)))
print(g(5), increment(square(5)))

power_of_two = partial(pow, 2)
cube = rpartial(pow, 3)
print(power_of_two(10), cube(4))

stats = ljuxt(min, max, sum, len)
print(stats([4, 8, 1, 9, 3]))

slug = rcompose(str.strip, str.lower, rpartial(str.replace, ' ', '-'))
print(slug('  Python Funcy Tutorial '))

compose(square, increment) first increments and then squares, so it is the same as square(increment(x)). rcompose reads in the order the functions run, which is convenient for data pipelines. The rpartial function fixes the last arguments: rpartial(pow, 3) computes the cube of its argument. ljuxt returns a list with the results of min, max, sum, and len. The last pipeline strips, lowercases, and hyphenates a title to create a URL slug.

$ python compose_funcs.py
36 36
26 26
1024 64
[1, 9, 25, 5]
python-funcy-tutorial

Combining predicates

A predicate is a function that returns true or false. Funcy can build new predicates from existing ones: complement negates a predicate, and all_fn, any_fn, and none_fn combine several of them. The isa function creates a type check.

predicates.py
from funcy import complement, all_fn, any_fn, none_fn, lfilter, isa

def is_even(n):
    return n % 2 == 0

def is_positive(n):
    return n > 0

values = [-4, -3, 0, 5, 8, 12, -7]

print(lfilter(complement(is_even), values))
print(lfilter(all_fn(is_even, is_positive), values))
print(lfilter(any_fn(is_even, is_positive), values))
print(lfilter(none_fn(is_even, is_positive), values))

data = [1, 'one', 2.5, None, [1], 'two']
print(lfilter(isa(str), data))
print(lfilter(isa(int, float), data))

The combined predicates are ordinary functions, so they can be passed to lfilter or any other function that expects a predicate. The all_fn(is_even, is_positive) predicate keeps only the positive even numbers, while none_fn keeps the numbers that are neither even nor positive. isa(int, float) works like isinstance with a tuple of types.

$ python predicates.py
[-3, 5, -7]
[8, 12]
[-4, 0, 5, 8, 12]
[-3, -7]
['one', 'two']
[1, 2.5]

Caching results

The memoize decorator remembers the results of a function and returns the stored result when the function is called again with the same arguments. It is similar to functools.cache, but gives direct access to the cache.

memo_fib.py
from funcy import memoize

calls = 0

@memoize
def fib(n):
    global calls
    calls += 1
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80), calls)
print(fib(90), calls)

print(len(fib.memory))
fib.invalidate(90)
print(fib(90), calls)

@memoize(key_func=str.lower)
def lookup(word):
    print('looking up', word)
    return len(word)

print(lookup('Falcon'), lookup('FALCON'), lookup('falcon'))

Thanks to the cache, computing the 80th Fibonacci number takes only 81 calls, and the 90th then needs just ten more. The cache is available as the memory attribute, and invalidate removes a single entry, so the next call computes fib(90) again; the smaller values are still cached, which costs one extra call. The key_func argument decides which calls share a cache entry. Here the three spellings of falcon share one entry, so the lookup runs only once.

$ python memo_fib.py
23416728348467685 81
2880067194370816120 91
91
2880067194370816120 92
looking up Falcon
6 6 6

Retrying calls

The retry decorator calls a function again when it raises one of the given exceptions. It is useful for network operations that fail now and then.

retry_calls.py
from funcy import retry

attempts = 0

@retry(3, errors=ConnectionError)
def fetch_rates():
    global attempts
    attempts += 1
    print('attempt', attempts)
    if attempts < 3:
        raise ConnectionError('server busy')
    return {'EUR': 1.0, 'USD': 1.16}

print(fetch_rates())

@retry(2, errors=ConnectionError)
def always_down():
    raise ConnectionError('host unreachable')

try:
    always_down()
except ConnectionError as e:
    print('gave up:', e)

The fetch_rates function simulates a server that fails twice before it answers. With retry(3, ...), the function gets three attempts, and the third one succeeds. When all attempts fail, the last exception is raised to the caller. In real code, we add a timeout argument to wait between the attempts; it can be a number of seconds or a function of the attempt number, such as timeout=lambda n: 2 ** n.

$ python retry_calls.py
attempt 1
attempt 2
attempt 3
{'EUR': 1.0, 'USD': 1.16}
gave up: host unreachable

Ignoring errors

The silent function wraps a function so that it returns None instead of raising any exception. The ignore decorator is more careful: it suppresses only the given exception types and can return a default value.

ignore_errors.py
from funcy import silent, ignore, lmap, lkeep

values = ['12', 'x', '7.5', '', '40']

print(lmap(silent(int), values))
print(lkeep(silent(float), values))

@ignore(ZeroDivisionError, default=float('inf'))
def ratio(a, b):
    return a / b

print(ratio(10, 4), ratio(1, 0))

@ignore(KeyError)
def price(item):
    return {'apple': 0.5, 'plum': 0.3}[item]

print(price('plum'), price('kiwi'))
try:
    ratio('a', 2)
except TypeError as e:
    print('not ignored:', e)

silent(int) turns the values that are not integers into None, and lkeep(silent(float), values) keeps only the values that convert. The ratio function returns infinity instead of raising ZeroDivisionError, and price returns None for unknown items. Other exceptions pass through: dividing a string still raises TypeError. Use silent only for small conversions like these, as it also hides real bugs.

$ python ignore_errors.py
[12, None, None, None, 40]
[12.0, 7.5, 40.0]
2.5 inf
0.3 None
not ignored: unsupported operand type(s) for /: 'str' and 'int'

Writing decorators

The decorator function turns a simple function into a decorator. Instead of writing nested wrapper functions, we get a call object that runs the decorated function when it is called.

own_decorator.py
from funcy import decorator

@decorator
def trace(call):
    print(f'-> {call._func.__name__}{call._args}')
    result = call()
    print(f'<- {result}')
    return result

@decorator
def clamp(call, low, high):
    return max(low, min(high, call()))

@trace
def add(a, b):
    return a + b

@clamp(0, 100)
def percent(part, whole):
    return part * 100 // whole

add(3, 4)
print(percent(30, 120), percent(300, 120), percent(-5, 120))
print(add.__name__)

Inside trace, call._func is the decorated function and call._args holds the positional arguments; call() runs the function. Extra parameters after call become decorator arguments, so clamp(0, 100) limits the result to the given range. Funcy also copies the name and docstring of the decorated function, as functools.wraps does. Compare this with the hand-written wrappers in Python decorators.

$ python own_decorator.py
-> add(3, 4)
<- 7
25 100 0
add

Processing a sales log

The last example combines several funcy functions to process a small sales log. Some lines are empty or broken, and one quantity is not a number.

sales_report.py
from funcy import (lkeep, silent, rcompose, lremove, group_by, walk_values,
                   lpluck, merge_with, partial)

LOG = """\
2026-11-02;Bratislava;apples;12
2026-11-02;Kosice;pears;7
2026-11-03;Bratislava;plums;x
2026-11-03;Zilina;apples;5

2026-11-04;Kosice;apples;10
2026-11-04;Bratislava;pears;4
broken line
2026-11-05;Zilina;plums;6
"""

def parse(line):
    day, city, product, qty = line.split(';')
    return {'day': day, 'city': city, 'product': product, 'qty': int(qty)}

clean = rcompose(str.strip, silent(parse))
records = lkeep(clean, LOG.splitlines())
print(len(records), 'valid records')

by_city = group_by(lambda r: r['city'], records)
totals = dict(walk_values(rcompose(partial(lpluck, 'qty'), sum), by_city))
print(totals)

per_product = merge_with(sum, *({r['product']: r['qty']} for r in records))
print(per_product)

print('best city:', max(totals, key=totals.get))

small = lremove(lambda r: r['qty'] >= 6, records)
print('small orders:', lpluck('day', small))

The clean pipeline strips a line and parses it; silent turns the broken lines into None, and lkeep drops them, which leaves six valid records. We group the records by city and replace each group with the sum of its quantities. Because group_by returns a defaultdict and walk_values keeps the type of its input, we convert the result to a plain dictionary. The per-product totals come from merging one small dictionary per record with merge_with(sum, ...).

$ python sales_report.py
6 valid records
{'Bratislava': 16, 'Kosice': 17, 'Zilina': 11}
{'apples': 27, 'pears': 11, 'plums': 6}
best city: Kosice
small orders: ['2026-11-03', '2026-11-04']

Source

funcy documentation, funcy on GitHub

In this article we have used funcy to split, chunk, and flatten sequences, to transform, merge, and group dictionaries, to work with nested data, and to compose functions and predicates. We have also used its memoize, retry, ignore, and decorator helpers. The standard library equivalents are covered in Python itertools, Python groupby function, Python operator module, and Python closures.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.