Built-in Functions Reference
The most frequently used Python built-in functions — no imports required.
Return the number of items in an object (string, list, dict, etc.).
Used In: Validation, boundary checks, CSV header counts.
len(obj)print(len('hello'))
print(len([1, 2, 3]))
print(len({'a': 1, 'b': 2}))5
3
2Time Complexity: O(1)
Related Methods: count()
Return the type (class) of an object.
Used In: Debugging, schema validation, type-based routing.
type(obj)print(type(42))
print(type('hello'))
print(type([1, 2]))<class 'int'>
<class 'str'>
<class 'list'>Time Complexity: O(1)
Related Methods: isinstance()
type(x) == int vs isinstance(x, int): isinstance() returns True for subclasses too; type() does exact match only.
Print objects to stdout (or a file), with configurable sep and end.
Used In: Debugging, logging output, CLI tools.
print(*objects, sep=' ', end='\n', file=sys.stdout)print('name', 'role', sep=' | ')
print('loading', end='...')
print('done')name | role
loading...doneTime Complexity: O(N)
Related Methods: logging.info()
Read a line of text from the user via stdin.
Used In: CLI scripts, interactive data pipelines.
input(prompt='')age = int(input('Enter age: '))
print(f'You are {age} years old.')You are 25 years old.Time Complexity: O(1)
Common Mistakes: Using input() result directly in arithmetic without casting to int/float raises TypeError.
Generate a lazy sequence of integers, useful for loops and indexing.
Used In: Loop indices, batch size splits, generating sequences.
range(stop) / range(start, stop, step)print(list(range(5)))
print(list(range(2, 10, 2)))[0, 1, 2, 3, 4]
[2, 4, 6, 8]Time Complexity: O(1) creation, O(N) iteration
Related Methods: enumerate()
Yield (index, value) pairs while iterating — avoids manual index tracking.
Used In: CSV row indexing, progress tracking, labeled iteration.
enumerate(iterable, start=0)rows = ['Alice,DE', 'Bob,DS', 'Carol,ML']
for i, row in enumerate(rows, start=1):
print(f'Row {i}: {row}')Row 1: Alice,DE
Row 2: Bob,DS
Row 3: Carol,MLTime Complexity: O(1) creation, O(N) iteration
Related Methods: zip()
enumerate() vs manual counter: enumerate() is safer and more readable than managing a separate counter variable.
Pair elements from multiple iterables together, producing tuples.
Used In: Pairing CSV columns, combining parallel lists.
zip(*iterables)names = ['Alice', 'Bob']
sals = [90000, 75000]
for name, sal in zip(names, sals):
print(f'{name}: ${sal:,}')Alice: $90,000
Bob: $75,000Time Complexity: O(1) creation, O(N) iteration
Related Methods: enumerate(), dict(zip())
zip() vs enumerate(): zip() pairs multiple iterables; enumerate() pairs an iterable with its indices.
Return a new sorted list from any iterable, with optional key and reverse.
Used In: Ranking results, sorting output files, leaderboards.
sorted(iterable, key=None, reverse=False)employees = [{'name': 'Bob', 'sal': 75000}, {'name': 'Alice', 'sal': 90000}]
ranked = sorted(employees, key=lambda e: e['sal'], reverse=True)
print(ranked[0]['name'])AliceTime Complexity: O(N log N) — Timsort
Related Methods: list.sort()
sorted() vs list.sort(): sorted() returns a new list; list.sort() mutates in-place and returns None.
Return a lazy reverse iterator over a sequence.
Used In: Backtracking, undo stacks, display reversal.
reversed(sequence)steps = ['extract', 'transform', 'load']
for step in reversed(steps):
print(step)load
transform
extractTime Complexity: O(1) creation, O(N) iteration
Related Methods: list[::-1]
reversed() vs [::-1]: reversed() creates a lazy iterator (O(1) memory); [::-1] creates a new copy (O(N) memory).
Return the sum of a numeric iterable, optionally with a start value.
Used In: Revenue totals, batch aggregation, scoring.
sum(iterable, start=0)orders = [120.50, 85.00, 340.75]
total = sum(orders)
print(f'Total: ${total:.2f}')Total: $546.25Time Complexity: O(N)
Related Methods: min(), max(), statistics.mean()
Return the smallest or largest item from an iterable, with optional key function.
Used In: Finding top/bottom records, validation bounds.
min(iterable, key=None) / max(iterable, key=None)records = [{'id': 3, 'score': 82}, {'id': 1, 'score': 95}, {'id': 2, 'score': 71}]
best = max(records, key=lambda r: r['score'])
print(best['id'])1Time Complexity: O(N)
Related Methods: sorted(), heapq.nlargest()
Return the absolute (positive) value of a number.
Used In: Error margins, distance calculations, financial deltas.
abs(x)print(abs(-42))
print(abs(-3.14))42
3.14Time Complexity: O(1)
Related Methods: math.fabs()
Round a number to a given number of decimal places.
Used In: Currency formatting, percentage display, precision control.
round(number, ndigits=0)print(round(3.14159, 2))
print(round(2.5))3.14
2Time Complexity: O(1)
Common Mistakes: Expecting round(2.5) == 3 — Python rounds to even, not always up.
Related Methods: math.floor(), math.ceil()
Test if any (or all) elements in an iterable evaluate to True.
Used In: Validation pipelines, required field checks, batch health checks.
any(iterable) / all(iterable)statuses = ['ok', 'ok', 'error']
print(any(s == 'error' for s in statuses))
print(all(s == 'ok' for s in statuses))True
FalseTime Complexity: O(N) worst case, O(1) best case
Related Methods: filter()
Apply a function to every element of an iterable, returning a lazy iterator.
Used In: Type casting columns, applying transformations.
map(func, iterable)prices = ['12.5', '99.0', '7.25']
floats = list(map(float, prices))
print(floats)[12.5, 99.0, 7.25]Time Complexity: O(1) creation, O(N) iteration
Related Methods: filter(), list comprehension
map() vs list comprehension: comprehension is more readable; map() is marginally faster for single built-in functions.
Select elements from an iterable where a function returns True.
Used In: Filtering null/empty records, removing invalid entries.
filter(func, iterable)orders = [150, 0, 320, 0, 75]
valid = list(filter(None, orders)) # removes falsy values
print(valid)[150, 320, 75]Time Complexity: O(1) creation, O(N) iteration
Related Methods: map(), list comprehension
Open a file and return a file object for reading or writing.
Used In: Reading configs, writing output files, ETL log writing.
open(file, mode='r', encoding=None)with open('data.csv', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(len(lines))100Time Complexity: O(1) open, O(N) read
Common Mistakes: Opening files without with blocks — file descriptors leak if an exception occurs before f.close().
Related Methods: pathlib.Path.read_text()
Check if an object is an instance of a class or tuple of classes.
Used In: Input validation, polymorphic dispatch, schema enforcement.
isinstance(obj, classinfo)x = 42
print(isinstance(x, int))
print(isinstance(x, (int, float)))True
TrueTime Complexity: O(1)
Related Methods: type()
isinstance() vs type(): isinstance(x, int) returns True for subclasses of int; type(x) == int only matches the exact class.
Return the unique memory address (id) or hash value of an object.
Used In: Caching, deduplication, identity checks.
id(obj) / hash(obj)a = 'hello'
b = 'hello'
print(id(a) == id(b)) # string interning
print(hash(42))True
42Time Complexity: O(1)
Common Mistakes: Calling hash() on a list raises TypeError — use tuple conversion first.
Inspect an object's attributes (dir) or read its documentation (help).
Used In: Debugging, REPL exploration, API discovery.
dir(obj) / help(obj)print([m for m in dir(str) if not m.startswith('_')][:5])['capitalize', 'casefold', 'center', 'count', 'encode']Time Complexity: O(N)
Related Methods: vars(), getattr()