PYTHON Reference Guide
Revision Time: 5 mins

Built-in Functions Reference

The most frequently used Python built-in functions — no imports required.

len()
Return: int

Return the number of items in an object (string, list, dict, etc.).

Used In: Validation, boundary checks, CSV header counts.

Syntax signature:len(obj)
Code snippet:
python
print(len('hello'))
print(len([1, 2, 3]))
print(len({'a': 1, 'b': 2}))
Expected Output:5 3 2

Time Complexity: O(1)

Related Methods: count()

Remember: Runs in O(1) for lists, strings, dicts, and tuples because Python stores length as a cached attribute.
type()
Return: type

Return the type (class) of an object.

Used In: Debugging, schema validation, type-based routing.

Syntax signature:type(obj)
Code snippet:
python
print(type(42))
print(type('hello'))
print(type([1, 2]))
Expected Output:<class 'int'> <class 'str'> <class 'list'>

Time Complexity: O(1)

Related Methods: isinstance()

Comparison:

type(x) == int vs isinstance(x, int): isinstance() returns True for subclasses too; type() does exact match only.

Remember: Use isinstance() for type-checking in production code — it supports inheritance correctly.
print()
Return: None

Print objects to stdout (or a file), with configurable sep and end.

Used In: Debugging, logging output, CLI tools.

Syntax signature:print(*objects, sep=' ', end='\n', file=sys.stdout)
Code snippet:
python
print('name', 'role', sep=' | ')
print('loading', end='...')
print('done')
Expected Output:name | role loading...done

Time Complexity: O(N)

Related Methods: logging.info()

Remember: Use file=sys.stderr to direct error messages to stderr instead of stdout.
input()
Return: str

Read a line of text from the user via stdin.

Used In: CLI scripts, interactive data pipelines.

Syntax signature:input(prompt='')
Code snippet:
python
age = int(input('Enter age: '))
print(f'You are {age} years old.')
Expected Output:You are 25 years old.

Time Complexity: O(1)

Common Mistakes: Using input() result directly in arithmetic without casting to int/float raises TypeError.

Remember: Always returns a string — cast to int() or float() for numeric processing.
range()
Return: range

Generate a lazy sequence of integers, useful for loops and indexing.

Used In: Loop indices, batch size splits, generating sequences.

Syntax signature:range(stop) / range(start, stop, step)
Code snippet:
python
print(list(range(5)))
print(list(range(2, 10, 2)))
Expected Output:[0, 1, 2, 3, 4] [2, 4, 6, 8]

Time Complexity: O(1) creation, O(N) iteration

Related Methods: enumerate()

Remember: range() is a lazy iterator — it does not allocate memory for all values. Use list(range()) only when you need an actual list.
enumerate()
Return: enumerate

Yield (index, value) pairs while iterating — avoids manual index tracking.

Used In: CSV row indexing, progress tracking, labeled iteration.

Syntax signature:enumerate(iterable, start=0)
Code snippet:
python
rows = ['Alice,DE', 'Bob,DS', 'Carol,ML']
for i, row in enumerate(rows, start=1):
    print(f'Row {i}: {row}')
Expected Output:Row 1: Alice,DE Row 2: Bob,DS Row 3: Carol,ML

Time Complexity: O(1) creation, O(N) iteration

Related Methods: zip()

Comparison:

enumerate() vs manual counter: enumerate() is safer and more readable than managing a separate counter variable.

Remember: Use start=1 to get human-readable 1-based numbering for display or reporting.
zip()
Return: zip

Pair elements from multiple iterables together, producing tuples.

Used In: Pairing CSV columns, combining parallel lists.

Syntax signature:zip(*iterables)
Code snippet:
python
names = ['Alice', 'Bob']
sals = [90000, 75000]
for name, sal in zip(names, sals):
    print(f'{name}: ${sal:,}')
Expected Output:Alice: $90,000 Bob: $75,000

Time Complexity: O(1) creation, O(N) iteration

Related Methods: enumerate(), dict(zip())

Comparison:

zip() vs enumerate(): zip() pairs multiple iterables; enumerate() pairs an iterable with its indices.

Remember: zip() stops at the shortest iterable. Use itertools.zip_longest() to keep all items with a fill value.
sorted()
Return: list

Return a new sorted list from any iterable, with optional key and reverse.

Used In: Ranking results, sorting output files, leaderboards.

Syntax signature:sorted(iterable, key=None, reverse=False)
Code snippet:
python
employees = [{'name': 'Bob', 'sal': 75000}, {'name': 'Alice', 'sal': 90000}]
ranked = sorted(employees, key=lambda e: e['sal'], reverse=True)
print(ranked[0]['name'])
Expected Output:Alice

Time Complexity: O(N log N) — Timsort

Related Methods: list.sort()

Comparison:

sorted() vs list.sort(): sorted() returns a new list; list.sort() mutates in-place and returns None.

Remember: sorted() never mutates the original; use list.sort() for in-place sorting.
reversed()
Return: reversed

Return a lazy reverse iterator over a sequence.

Used In: Backtracking, undo stacks, display reversal.

Syntax signature:reversed(sequence)
Code snippet:
python
steps = ['extract', 'transform', 'load']
for step in reversed(steps):
    print(step)
Expected Output:load transform extract

Time Complexity: O(1) creation, O(N) iteration

Related Methods: list[::-1]

Comparison:

reversed() vs [::-1]: reversed() creates a lazy iterator (O(1) memory); [::-1] creates a new copy (O(N) memory).

Remember: Returns a lazy iterator — wrap in list() only when you need random access to the reversed sequence.
sum()
Return: int | float

Return the sum of a numeric iterable, optionally with a start value.

Used In: Revenue totals, batch aggregation, scoring.

Syntax signature:sum(iterable, start=0)
Code snippet:
python
orders = [120.50, 85.00, 340.75]
total = sum(orders)
print(f'Total: ${total:.2f}')
Expected Output:Total: $546.25

Time Complexity: O(N)

Related Methods: min(), max(), statistics.mean()

Remember: Use sum() with a generator expression for memory-efficient totalling: sum(x**2 for x in data).
min() / max()
Return: T

Return the smallest or largest item from an iterable, with optional key function.

Used In: Finding top/bottom records, validation bounds.

Syntax signature:min(iterable, key=None) / max(iterable, key=None)
Code snippet:
python
records = [{'id': 3, 'score': 82}, {'id': 1, 'score': 95}, {'id': 2, 'score': 71}]
best = max(records, key=lambda r: r['score'])
print(best['id'])
Expected Output:1

Time Complexity: O(N)

Related Methods: sorted(), heapq.nlargest()

Remember: Use the key parameter to compare by a specific field instead of natural ordering.
abs()
Return: int | float

Return the absolute (positive) value of a number.

Used In: Error margins, distance calculations, financial deltas.

Syntax signature:abs(x)
Code snippet:
python
print(abs(-42))
print(abs(-3.14))
Expected Output:42 3.14

Time Complexity: O(1)

Related Methods: math.fabs()

Remember: Works on int, float, and complex numbers. For complex, returns the magnitude.
round()
Return: int | float

Round a number to a given number of decimal places.

Used In: Currency formatting, percentage display, precision control.

Syntax signature:round(number, ndigits=0)
Code snippet:
python
print(round(3.14159, 2))
print(round(2.5))
Expected Output:3.14 2

Time Complexity: O(1)

Common Mistakes: Expecting round(2.5) == 3 — Python rounds to even, not always up.

Related Methods: math.floor(), math.ceil()

Remember: Python uses banker's rounding (round half to even) — round(2.5) returns 2, not 3.
any() / all()
Return: bool

Test if any (or all) elements in an iterable evaluate to True.

Used In: Validation pipelines, required field checks, batch health checks.

Syntax signature:any(iterable) / all(iterable)
Code snippet:
python
statuses = ['ok', 'ok', 'error']
print(any(s == 'error' for s in statuses))
print(all(s == 'ok' for s in statuses))
Expected Output:True False

Time Complexity: O(N) worst case, O(1) best case

Related Methods: filter()

Remember: Both short-circuit — any() stops at the first True, all() stops at the first False.
map()
Return: map

Apply a function to every element of an iterable, returning a lazy iterator.

Used In: Type casting columns, applying transformations.

Syntax signature:map(func, iterable)
Code snippet:
python
prices = ['12.5', '99.0', '7.25']
floats = list(map(float, prices))
print(floats)
Expected Output:[12.5, 99.0, 7.25]

Time Complexity: O(1) creation, O(N) iteration

Related Methods: filter(), list comprehension

Comparison:

map() vs list comprehension: comprehension is more readable; map() is marginally faster for single built-in functions.

Remember: map() returns a lazy iterator — wrap in list() only when you need the full result immediately.
filter()
Return: filter

Select elements from an iterable where a function returns True.

Used In: Filtering null/empty records, removing invalid entries.

Syntax signature:filter(func, iterable)
Code snippet:
python
orders = [150, 0, 320, 0, 75]
valid = list(filter(None, orders))  # removes falsy values
print(valid)
Expected Output:[150, 320, 75]

Time Complexity: O(1) creation, O(N) iteration

Related Methods: map(), list comprehension

Remember: Pass None as the function to remove all falsy values (0, '', None, False, []).
open()
Return: TextIOWrapper

Open a file and return a file object for reading or writing.

Used In: Reading configs, writing output files, ETL log writing.

Syntax signature:open(file, mode='r', encoding=None)
Code snippet:
python
with open('data.csv', 'r', encoding='utf-8') as f:
    lines = f.readlines()
print(len(lines))
Expected Output:100

Time 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()

Remember: Always use the with statement — it guarantees the file is closed even if an exception occurs.
isinstance()
Return: bool

Check if an object is an instance of a class or tuple of classes.

Used In: Input validation, polymorphic dispatch, schema enforcement.

Syntax signature:isinstance(obj, classinfo)
Code snippet:
python
x = 42
print(isinstance(x, int))
print(isinstance(x, (int, float)))
Expected Output:True True

Time Complexity: O(1)

Related Methods: type()

Comparison:

isinstance() vs type(): isinstance(x, int) returns True for subclasses of int; type(x) == int only matches the exact class.

Remember: Prefer isinstance() over type() == for type checks — isinstance() supports inheritance.
id() / hash()
Return: int

Return the unique memory address (id) or hash value of an object.

Used In: Caching, deduplication, identity checks.

Syntax signature:id(obj) / hash(obj)
Code snippet:
python
a = 'hello'
b = 'hello'
print(id(a) == id(b))  # string interning
print(hash(42))
Expected Output:True 42

Time Complexity: O(1)

Common Mistakes: Calling hash() on a list raises TypeError — use tuple conversion first.

Remember: hash() requires the object to be immutable (strings, ints, tuples). Lists and dicts are not hashable.
dir() / help()
Return: list | None

Inspect an object's attributes (dir) or read its documentation (help).

Used In: Debugging, REPL exploration, API discovery.

Syntax signature:dir(obj) / help(obj)
Code snippet:
python
print([m for m in dir(str) if not m.startswith('_')][:5])
Expected Output:['capitalize', 'casefold', 'center', 'count', 'encode']

Time Complexity: O(N)

Related Methods: vars(), getattr()

Remember: dir() is invaluable when exploring unfamiliar APIs — it lists every method and attribute.