Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

Python Built-in Functions: Tested Examples and Common Pitfalls

Published

Python

Python’s built-in functions and types are available without an import. They cover common tasks such as inspecting values, converting input, sorting data and opening files. Choose them for clear behavior, not because every built-in call is automatically faster than an equivalent loop.

This reference uses Python 3.12.14. Examples include assertions that show expected results. Assertions are tests, not a replacement for required input validation. The two input/file functions are tested with controlled input and a disposable file; they do not run an interactive prompt or open a file merely when defined.

Inspect length and type

len() counts items in a sized object. For a string it counts Unicode code points, not necessarily visible characters or screen columns. type() identifies the exact type; isinstance() also recognizes subclasses. Choose deliberately: a Boolean is an instance of int, which may not match your input contract.

services = ["web", "mail", "dns"]
assert len(services) == 3
assert len({"web": 443}) == 1
assert len("e\u0301") == 2
assert type(services) is list
assert isinstance(services, (list, tuple))
assert isinstance(True, int)
assert type(True) is not int
print(len(services), type(services).__name__)

Convert values without confusing text and truth

str(), int(), float() and bool() have different conversion rules. In particular, bool("False") is true because the string is non-empty. Parse a textual setting against the accepted values instead of treating truthiness as a Boolean parser. An integer conversion from a float truncates toward zero; it does not round.

assert str(443) == "443"
assert int(" 12 ") == 12
assert int(-2.9) == -2
assert float("1.5") == 1.5
assert bool(0) is False
assert bool("False") is True

def parse_enabled(text):
    normalized = text.strip().lower()
    if normalized == "true":
        return True
    if normalized == "false":
        return False
    raise ValueError("Use true or false")

assert parse_enabled(" TRUE ") is True
assert parse_enabled("false") is False
print(parse_enabled("false"))

Build collections and understand what changes

list() and tuple() consume an iterable in iteration order. dict() can consume key/value pairs; later entries replace earlier values for an equal key. set() removes duplicate values and does not promise iteration order. These constructors are not deep-copy operations.

assert list("web") == ["w", "e", "b"]
assert tuple([80, 443]) == (80, 443)
assert dict([("web", 80), ("web", 443)]) == {"web": 443}
assert set(["web", "mail", "web"]) == {"web", "mail"}

original = [[1]]
copied = list(original)
copied[0].append(2)
assert original == [[1, 2]]
assert copied is not original
assert copied[0] is original[0]
print(copied)

Transform and select items with map and filter

In Python 3, map() and filter() return iterators. Work happens as you consume them, and an exhausted iterator does not start again. A comprehension can express the same task more directly. lambda is an expression that creates a function, not a built-in function itself.

values = [1, 2, 3, 4]
doubled = map(lambda value: value * 2, values)
assert list(doubled) == [2, 4, 6, 8]
assert list(doubled) == []
evens = list(filter(lambda value: value % 2 == 0, values))
assert evens == [2, 4]
assert evens == [value for value in values if value % 2 == 0]
print(evens)

reduce() belongs to the standard-library functools module and requires an import. Use a simpler dedicated operation, such as sum(), when it states the intent more clearly. An initial value defines the result for an empty input.

from functools import reduce

total = reduce(lambda accumulated, value: accumulated + value, [2, 3, 4], 0)
assert total == 9
assert total == sum([2, 3, 4])
assert reduce(lambda accumulated, value: accumulated + value, [], 0) == 0
print(total)

Test collections with any and all

any() looks for a truthy item; all() checks whether every item is truthy. They do not require the objects to be identical to True. Both stop when the answer is known. For an empty iterable, any() is false and all() is true, so check non-emptiness separately when your rule requires at least one item.

assert any([0, "", "web"]) is True
assert all([1, "web"]) is True
assert any([]) is False
assert all([]) is True

visited = []
def flags():
    for value in [False, True, True]:
        visited.append(value)
        yield value

assert any(flags()) is True
assert visited == [False, True]
print(visited)

Use numeric helpers with explicit boundary behavior

abs() gives a magnitude, pow() exponentiation, and min()/max() select an extreme value. sum() adds values and defaults to zero for an empty iterable. An empty min() or max() needs a supplied default or raises ValueError.

For built-in numeric types, halfway rounding uses the even choice. Binary floating-point representation can make decimal-looking values round unexpectedly. Do not assume round() implements your application’s decimal precision or accounting rules.

values = [5, 12, 3]
assert abs(-8) == 8
assert pow(2, 5) == 32
assert pow(2, 5, 7) == 4
assert min(values) == 3
assert max(values) == 12
assert sum(values) == 20
assert sum([]) == 0
assert min([], default=None) is None
assert round(2.5) == 2
assert round(3.5) == 4
assert round(2.675, 2) == 2.67
print(sum(values))

Sort a new list or traverse a sequence backward

sorted() creates a list and supports key and reverse. It does not rearrange the input list. reversed() produces a reverse iterator for an object with the reverse or sequence protocol; it does not accept every possible iterable. Neither operation is the same as a recursive or deep copy.

services = ["mail", "web", "dns"]
assert sorted(services) == ["dns", "mail", "web"]
assert sorted(services, reverse=True) == ["web", "mail", "dns"]
assert sorted(services, key=len) == ["web", "dns", "mail"]
assert services == ["mail", "web", "dns"]
backward = reversed(services)
assert list(backward) == ["dns", "web", "mail"]
assert list(backward) == []
print(sorted(services))

Inspect identity, documentation and attributes

id() identifies an object during its lifetime; it is not a portable promise of a memory address. An identity can be reused after an object is gone. Use is for identity and == for equality. hex() formats an integer in hexadecimal; it does not establish where an object lives.

original = [1, 2]
alias = original
separate = [1, 2]
assert id(alias) == id(original)
assert alias is original
assert separate == original and separate is not original
assert id(separate) != id(original)
assert hex(255) == "0xff"
assert "append" in dir([])
help(len)

help() displays documentation and dir() provides a useful attribute list, not an exhaustive security check. Dynamic attribute functions can invoke properties or other object behavior. In particular, hasattr() attempts attribute access and handles AttributeError; it is not a side-effect-free inspection of raw storage.

class Settings:
    pass

settings = Settings()
setattr(settings, "mode", "preview")
assert getattr(settings, "mode") == "preview"
assert hasattr(settings, "mode")
assert getattr(settings, "missing", "default") == "default"
delattr(settings, "mode")
assert not hasattr(settings, "mode")
print(getattr(settings, "mode", "not set"))

Do not pass arbitrary user-controlled attribute names into setattr(). Define the permitted configuration fields and their validation first. For known fields, ordinary attribute access is usually clearer.

Keep input and file operations explicit

input() returns text without the trailing newline. Convert and validate it before using it as a count. This function prompts only when called; its tests supply controlled responses instead of waiting for a person.

def read_count():
    raw = input("Job count: ")
    count = int(raw)
    if count < 0:
        raise ValueError("Job count cannot be negative")
    print("Accepted count:", count)
    return count

open() can raise errors for missing files, permissions or decoding. Use an explicit encoding for text and a with block for closure. Mode "r" reads; "w" truncates an existing file, while "x" refuses an existing path. This function is read-only and opens only the path supplied by its caller.

def first_line(path):
    with open(path, "r", encoding="utf-8") as stream:
        return stream.readline().rstrip("\r\n")

Verification: All twelve examples were checked on Python 3.12.14. Tests include iterator exhaustion, conversion errors, truthiness, shallow copies, attribute side effects, controlled input and file closure on success and decoding failure. No customer files or real interactive input were used.

References: Python’s built-in reference and functools.reduce. Related: collection choices and truthiness and logical operators.

Related guides

Account services are unavailable until the production backend is configured.