Functional Functions
These functions allow you to apply operations in a declarative and functional way on data collections, such as lists or tuples. They are especially useful when you need to apply a function to many elements (map), filter according to conditions (filter), combine data (zip), or generate numeric sequences (range). Their use favors a cleaner, more compact, and expressive programming style.
Function | Description |
---|---|
map() | Applies a function to each element of an iterable and returns a new iterable. |
filter() | Filters the elements of an iterable according to a given condition. |
zip() | Joins several iterables into ordered pairs, such as tuples. |
range() | Generates a sequence of numbers, generally used in loops. |
all() | Returns True if all elements of an iterable are true. |
any() | Returns True if at least one element is true. |
Below I will explain in more detail how these functions work:
Typical use: Apply a function to each element of an iterable and return a new iterable.
numbers = [1, 2, 3, 4]squared = map(lambda x: x ** 2, numbers)print(list(squared))
Output:
[1, 4, 9, 16]
filter()
Section titled “filter()”Typical use: Filter the elements of an iterable that meet a condition.
numbers = [10, 15, 20, 25]greater_than_15 = filter(lambda x: x > 15, numbers)print(list(greater_than_15))
Output:
[20, 25]
Typical use: Combine multiple iterables into ordered pairs (tuples).
names = ['Ana', 'Luis', 'Sofía']ages = [28, 34, 25]pairs = zip(names, ages)print(list(pairs))
Output:
[('Ana', 28), ('Luis', 34), ('Sofía', 25)]
range()
Section titled “range()”Typical use: Generate a numeric sequence, commonly used in loops.
for number in range(0, 10, 2): # From 0 to 8 in steps of 2 print(number, end='')
Output:
02468
Typical use: Check if all elements of an iterable are true.
values = [True, 1, 5 > 2]print(all(values))
Output:
True
Typical use: Check if at least one of the elements of an iterable is true.
values = [0, '', None, 7]print(any(values))
Output:
True