Function Composition in Python
In Python, built-in functions are incredibly versatile on their own, but their true power is
unlocked when you link them together. This concept, known as function composition,
involves taking the output of one function and feeding it directly as the input to another
function.
How to Link Functions
Functions in Python can be linked in several ways, depending on readability and the data
structures involved:
1. NESTED FUNCTION CALLS F(G(X))
The most direct way to link functions is to nest them. The innermost function executes first,
passing its return value outward.
The Python Built-In
# input() gets a string, int() converts it, abs() finds magnitude
absolute_value = abs(int(input("Enter a number: ")))
Functions
2. FUNCTIONAL PIPELINES (MAP & FILTER )
Handbook
When working with iterables (like lists or streams of data), functions like map() and
filter() act as bridges, applying functions iteratively across the data.
# Converting strings to ints, filtering negatives, summing the result
A Comprehensive Guide to Syntax, Usage,
raw_data = ["10", "-5", "20", "-1"]
and Composition
total = sum(filter(lambda x: x > 0, map(int, raw_data)))
# Output: 30
3. THE 'KEY' ARGUMENT PARADIGM
Functions like max(), min(), and sorted() accept a key argument. By passing another
function (like len or abs) to this argument, you effectively link the evaluation metric of the
outer function to the logic of the inner function.
When to Link? Link functions when transforming data streams, parsing user input, or
reducing lists into single values. It creates concise, expressive, and efficient code without
the need for verbose intermediary variables.
1. Mathematical & Numeric Functions
Functions used for numerical calculations, aggregations, and mathematical evaluations.
abs()
abs(x)
WHAT IT DOES
Returns the absolute (positive) value of a number.
WHEN TO USE IT
When you need the magnitude of a value regardless of its sign, such as calculating
distance or differences.
HOW TO LINK IT
Often used within a map() or as a key in max()/min().
EXAMPLE
numbers = [-5, -2, 0, 3, 4]
# Linking abs with max to find the number with the largest magnitude
max_mag = max(numbers, key=abs)
print(max_mag) # Output: -5
divmod()
divmod(a, b)
WHAT IT DOES
Takes two numbers and returns a pair of numbers (a tuple) consisting of their
quotient and remainder.
WHEN TO USE IT
When you need both the result of integer division and the remainder simultaneously
(e.g., converting seconds into minutes and seconds).
HOW TO LINK IT
Often unpacked directly into two variables.
EXAMPLE
total_seconds = 250
minutes, seconds = divmod(total_seconds, 60)
print(f"{minutes}m {seconds}s") # Output: 4m 10s
max()
max(iterable, *[, key, default]) OR max(arg1, arg2, *args[, key])
WHAT IT DOES
Returns the largest item in an iterable or the largest of two or more arguments.
WHEN TO USE IT
Whenever you need to find the highest value, longest string, or largest object based
on a specific attribute.
HOW TO LINK IT
Powerfully linked with custom 'key' functions or lambda expressions to define
'largest'.
EXAMPLE
words = ['apple', 'banana', 'cherry', 'kiwi']
# Linked with len() to find the longest word
longest = max(words, key=len)
print(longest) # Output: banana
min()
min(iterable, *[, key, default]) OR min(arg1, arg2, *args[, key])
WHAT IT DOES
Returns the smallest item in an iterable or the smallest of two or more arguments.
WHEN TO USE IT
Whenever you need to find the lowest value or smallest object.
HOW TO LINK IT
Similar to max(), extremely useful when linked with the 'key' argument.
EXAMPLE
words = ['apple', 'banana', 'cherry', 'kiwi']
# Linked with len() to find the shortest word
shortest = min(words, key=len)
print(shortest) # Output: kiwi
pow()
pow(base, exp[, mod])
WHAT IT DOES
Returns base to the power exp. If mod is present, returns base to the power exp,
modulo mod.
WHEN TO USE IT
Used for exponentiation. The three-argument form is heavily used in cryptography
for modular exponentiation as it is far more efficient than pow(base, exp) % mod.
HOW TO LINK IT
Can be linked with mapping functions for polynomial calculations.
EXAMPLE
# Efficient modular exponentiation
result = pow(3, 4, 5) # (3^4) % 5 = 81 % 5 = 1
print(result)
round()
round(number[, ndigits])
WHAT IT DOES
Return number rounded to ndigits precision after the decimal point.
WHEN TO USE IT
When you need to clean up floating-point artifacts or present numbers in a human-
readable format (e.g., currency).
HOW TO LINK IT
Often linked with map() to round an entire list of floats.
EXAMPLE
prices = [19.999, 15.001, 10.5]
# Linking map with round
rounded_prices = list(map(lambda x: round(x, 2), prices))
print(rounded_prices) # Output: [20.0, 15.0, 10.5]
sum()
sum(iterable, /, start=0)
WHAT IT DOES
Sums start and the items of an iterable from left to right and returns the total.
WHEN TO USE IT
When you need to calculate the total of a list of numbers.
HOW TO LINK IT
Frequently linked with generator expressions or map() to transform data before
summing.
EXAMPLE
data = [{'val': 10}, {'val': 20}, {'val': 30}]
# Linking sum with a generator expression
total = sum(item['val'] for item in data)
print(total) # Output: 60
2. Type Conversion & Object Creation
Functions used to convert variables from one type to another, or instantiate basic data
structures.
int()
int([x]) OR int(x, base=10)
WHAT IT DOES
Returns an integer object constructed from a number or string x.
WHEN TO USE IT
Converting user input (which is always a string) to an integer, or truncating floats.
HOW TO LINK IT
Wrapped around input() or map().
EXAMPLE
# Linking input(), split(), map(), and list()
# User types: 10 20 30
numbers = list(map(int, "10 20 30".split()))
print(numbers) # Output: [10, 20, 30]
float()
float([x])
WHAT IT DOES
Returns a floating point number constructed from a number or string x.
WHEN TO USE IT
When parsing decimal numbers from text or doing division that requires float
representations.
HOW TO LINK IT
Used heavily in data parsing pipelines.
EXAMPLE
str_values = ['1.5', '2.5', '3.0']
floats = [float(x) for x in str_values]
bool()
bool([x])
WHAT IT DOES
Returns a Boolean value, i.e. one of True or False.
WHEN TO USE IT
When you need to explicitly test the truthiness of an object.
HOW TO LINK IT
Often linked with filter() to remove falsy values (None, 0, empty strings) from an
iterable.
EXAMPLE
mixed_data = [1, 0, 'hello', '', None, [1, 2], []]
# Linking filter with bool removes all falsy values
truthy_data = list(filter(bool, mixed_data))
print(truthy_data) # Output: [1, 'hello', [1, 2]]
str()
str(object='') OR str(object=b'', encoding='utf-8', errors='strict')
WHAT IT DOES
Returns a string version of an object.
WHEN TO USE IT
Whenever you need to concatenate non-strings with strings, or display objects to the
user.
HOW TO LINK IT
Used with map() or join() to format lists into strings.
EXAMPLE
numbers = [1, 2, 3, 4]
# Linked with map and join
csv_string = ", ".join(map(str, numbers))
print(csv_string) # Output: 1, 2, 3, 4
list, tuple, set, dict()
list([iterable]), tuple([iterable]), set([iterable]), dict(**kwarg)
WHAT IT DOES
Constructors for standard Python data collections.
WHEN TO USE IT
When you need to convert an iterator/generator into a concrete collection, or remove
duplicates (using set).
HOW TO LINK IT
Wraps functional outputs like map(), filter(), or zip() to force execution and store
results.
EXAMPLE
keys = ['a', 'b', 'c']
values = [1, 2, 3]
# Linking dict() and zip() to create a dictionary from two lists
my_dict = dict(zip(keys, values))
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
3. Iterable & Iterator Functions
Powerful functions for traversing, evaluating, and modifying sequences and generators.
all()
all(iterable)
WHAT IT DOES
Returns True if all elements of the iterable are true (or if the iterable is empty).
WHEN TO USE IT
Validating that a series of conditions have all been met.
HOW TO LINK IT
Extremely powerful when linked with generator expressions for conditional checks.
EXAMPLE
passwords = ['Pass123', 'Admin!23', 'short']
# Check if ALL passwords are at least 6 characters
is_valid = all(len(p) >= 6 for p in passwords)
print(is_valid) # Output: False
any()
any(iterable)
WHAT IT DOES
Returns True if any element of the iterable is true. If empty, returns False.
WHEN TO USE IT
Checking if at least one condition is met in a collection.
HOW TO LINK IT
Linked with comprehensions to search for a specific property without writing a full
loop.
EXAMPLE
files = ['[Link]', '[Link]', '[Link]']
# Check if ANY file is a Python script
has_python = any([Link]('.py') for f in files)
print(has_python) # Output: True
enumerate()
enumerate(iterable, start=0)
WHAT IT DOES
Returns an enumerate object. It yields pairs containing a count (from start) and a
value yielded by the iterable argument.
WHEN TO USE IT
When looping through a sequence and you need both the item and its index.
HOW TO LINK IT
Often used in for loops or wrapped in dict() to map indices to values.
EXAMPLE
tasks = ['wash car', 'buy groceries', 'clean room']
# Linked with a for loop for formatting
for index, task in enumerate(tasks, start=1):
print(f"{index}. {task}")
filter()
filter(function, iterable)
WHAT IT DOES
Constructs an iterator from elements of iterable for which function returns true.
WHEN TO USE IT
When you need to extract a subset of data that meets specific criteria.
HOW TO LINK IT
Often linked with lambda functions and wrapped in list() to manifest the result.
EXAMPLE
scores = [45, 92, 78, 33, 85]
# Link filter with a lambda and list
passing_scores = list(filter(lambda x: x >= 50, scores))
print(passing_scores) # Output: [92, 78, 85]
len()
len(s)
WHAT IT DOES
Returns the length (the number of items) of an object.
WHEN TO USE IT
When you need to know how many elements are in a list, string, or dictionary.
HOW TO LINK IT
Frequently used as a 'key' in min()/max()/sorted() functions.
EXAMPLE
words = ['a', 'very', 'long', 'word', 'indeed']
# Linking sorted() with len() to sort by string length
ordered = sorted(words, key=len)
print(ordered) # Output: ['a', 'long', 'word', 'very', 'indeed']
map()
map(function, iterable, ...)
WHAT IT DOES
Returns an iterator that applies function to every item of iterable, yielding the results.
WHEN TO USE IT
When you need to transform all items in a list in the same way (e.g., converting
strings to ints, or squaring numbers).
HOW TO LINK IT
The cornerstone of functional linking in Python. Often wrapped in list() or sum().
EXAMPLE
celsius = [0, 10, 20, 30]
# Linking map with a conversion function
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit) # Output: [32.0, 50.0, 68.0, 86.0]
sorted()
sorted(iterable, /, *, key=None, reverse=False)
WHAT IT DOES
Returns a new sorted list from the items in iterable.
WHEN TO USE IT
When you need elements in order without modifying the original collection.
HOW TO LINK IT
Highly versatile when linked with custom functions, itemgetter, or attrgetter via the
'key' argument.
EXAMPLE
students = [{'name': 'Alice', 'grade': 85}, {'name': 'Bob', 'grade':
92}]
# Linking sorted with a lambda to sort by dictionary key
ranked = sorted(students, key=lambda s: s['grade'], reverse=True)
print(ranked)
zip()
zip(*iterables, strict=False)
WHAT IT DOES
Iterates over several iterables in parallel, producing tuples with an item from each
one.
WHEN TO USE IT
When you need to pair up elements from two or more lists simultaneously.
HOW TO LINK IT
Often linked with dict() to merge keys and values, or unpacked in a for loop.
EXAMPLE
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
# Linking zip to iterate in parallel
for name, age in zip(names, ages):
print(f"{name} is {age}")
4. Input, Output & File Operations
Functions responsible for interacting with the file system and user console.
input()
input([prompt])
WHAT IT DOES
Reads a line from input, converts it to a string (stripping a trailing newline), and
returns that.
WHEN TO USE IT
Gathering interactive input from a user in a terminal.
HOW TO LINK IT
Almost always linked with string methods (like .strip() or .split()) and type converters
(like int()).
EXAMPLE
# Linking input -> split -> map -> list
user_data = list(map(int, input("Enter numbers separated by space:
").split()))
print()
print(*objects, sep=' ', end='\n', file=None, flush=False)
WHAT IT DOES
Prints objects to the text stream file, separated by sep and followed by end.
WHEN TO USE IT
Displaying output to the terminal or writing quick logs.
HOW TO LINK IT
Linked with [Link]() or f-strings for complex message assembly before printing.
EXAMPLE
items = ['apple', 'banana', 'orange']
# Customizing print with sep
print(*items, sep=' | ')
# Output: apple | banana | orange
open()
open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, closefd=True, opener=None)
WHAT IT DOES
Opens file and returns a corresponding file object.
WHEN TO USE IT
Reading from or writing to files on the filesystem.
HOW TO LINK IT
Should always be linked with the 'with' statement (context manager) to ensure files
are closed safely.
EXAMPLE
data = ["Line 1", "Line 2"]
# Linking open with a context manager
with open('[Link]', 'w', encoding='utf-8') as f:
for line in data:
[Link](line + '\n')
5. Object, Class & Scope Functions
Functions used for introspection, dynamic attribute access, and scope evaluation.
isinstance()
isinstance(object, classinfo)
WHAT IT DOES
Returns True if the object argument is an instance of the classinfo argument.
WHEN TO USE IT
Type checking before performing an operation, or implementing polymorphic
behavior.
HOW TO LINK IT
Often used in list comprehensions or filter() to extract specific types from
heterogeneous lists.
EXAMPLE
mixed = [1, 'two', 3.0, 'four', 5]
# Linking isinstance inside a comprehension
strings_only = [x for x in mixed if isinstance(x, str)]
print(strings_only) # Output: ['two', 'four']
getattr()
getattr(object, name[, default])
WHAT IT DOES
Returns the value of the named attribute of object.
WHEN TO USE IT
When you need to access an object's property dynamically using a string variable.
HOW TO LINK IT
Frequently linked with hasattr() to safely retrieve values without raising
AttributeError.
EXAMPLE
class Person:
name = "Alice"
field = "name"
# Dynamic access
print(getattr(Person, field, "Unknown")) # Output: Alice
type()
type(object) OR type(name, bases, dict, **kwds)
WHAT IT DOES
With one argument, return the type of an object. With three arguments, return a new
type object.
WHEN TO USE IT
For simple type checking (though isinstance is preferred) or dynamic class creation.
HOW TO LINK IT
Linked with debugging tools or dynamic factory patterns.
EXAMPLE
x = 42
print(type(x)) # Output:
6. Formatting & Miscellaneous
A collection of string formatters, binary converters, and helpful built-ins.
bin / oct / hex()
bin(x) / oct(x) / hex(x)
WHAT IT DOES
Converts an integer number to a binary/octal/hexadecimal string.
WHEN TO USE IT
Working with bitwise operations, memory addresses, or specialized data formats.
HOW TO LINK IT
Often linked with string slicing [2:] to remove the '0b', '0o', or '0x' prefix.
EXAMPLE
num = 255
print(hex(num)[2:].upper()) # Output: FF
ord / chr()
ord(c) / chr(i)
WHAT IT DOES
ord() returns integer representing Unicode character. chr() returns string
representing character for unicode integer.
WHEN TO USE IT
Encoding, deciphering text, or cryptography tasks.
HOW TO LINK IT
Linked together in map() pipelines to shift characters (like a Caesar cipher).
EXAMPLE
# Caesar cipher shift by 1
msg = "abc"
shifted = "".join(chr(ord(c) + 1) for c in msg)
print(shifted) # Output: bcd
help()
help([object])
WHAT IT DOES
Invoke the built-in help system.
WHEN TO USE IT
When you need interactive documentation in the REPL.
HOW TO LINK IT
Typically used standalone, not linked.
EXAMPLE
help(print)