Skip to main content Brad's PyNotes

Built-in Functions: Python's Essential Toolkit

TL;DR

Python’s built-in functions like map(), filter(), zip(), and enumerate() provide powerful, memory-efficient ways to process data without explicit loops.

Interesting!

The any() and all() functions can short-circuit evaluation - any() returns True as soon as it finds one truthy value, making them incredibly efficient for large datasets.

Essential Functions

python code snippet start

# map() - Transform every element
numbers = list(map(int, ['1', '2', '3']))
squares = list(map(lambda x: x**2, range(5)))

# filter() - Select elements
evens = list(filter(lambda x: x % 2 == 0, range(10)))

# zip() - Combine iterables
names = ['Alice', 'Bob']
ages = [25, 30]
combined = list(zip(names, ages))  # [('Alice', 25), ('Bob', 30)]

# enumerate() - Add indices
for i, item in enumerate(['a', 'b', 'c']):
    print(f"{i}: {item}")

python code snippet end

Logic and Aggregation

python code snippet start

# any() and all()
scores = [85, 92, 78, 96]
has_high = any(score > 90 for score in scores)  # True
all_passing = all(score >= 70 for score in scores)  # True

# min(), max(), sum()
print(min(scores))  # 78
print(max(scores, key=lambda x: x))  # 96
print(sum(scores))  # 351

python code snippet end

Python’s built-in functions form the foundation of elegant, efficient programming.

Built-in functions work seamlessly with itertools and functools for powerful functional programming patterns. These functions embody Zen of Python principles and integrate naturally with collections containers for data processing.

Reference: Python Built-in Functions Documentation