Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Built-in Functions: A Practical Guide

Python built-in functions are always available without imports. This guide explains key functions for type conversion, iteration, attribute access, and I/O with practical examples.

~5 min readPython
#python#built-in functions#python standard library#code efficiency
Illustration of Python built-in functions as a set of tools for code transformation and data handling.

Python ships with a set of built-in functions that are always available without imports. They cover common operations like type conversion, iteration, attribute access, and input/output. Understanding them reduces boilerplate and makes code more readable. This article focuses on the most frequently used built-in functions, how they behave, and when to choose them over manual loops or custom helpers.

Core Data Transformation Functions

map() and filter() are the primary functional tools. map() applies a function to every item in an iterable and returns an iterator. filter() keeps only items that satisfy a predicate. Both are lazy, meaning they produce values on demand rather than building a list immediately.

python
numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, numbers) evens = filter(lambda x: x % 2 == 0, numbers) print(list(squared)) # [1, 4, 9, 16, 25] print(list(evens)) # [2, 4]

Because they return iterators, you must consume them with list(), tuple(), or a loop. If you need the result multiple times, convert it to a sequence once. For simple transformations, a list comprehension is often more readable:

python
squared = [x ** 2 for x in numbers] evens = [x for x in numbers if x % 2 == 0]

The choice depends on context. map() and filter() shine when you already have a named function and want to avoid a lambda. They also compose well with other functional tools like functools.reduce().

zip() is another transformation function that pairs elements from multiple iterables. It stops at the shortest input by default:

python
names = ["Alice", "Bob", "Charlie"] scores = [85, 92, 78] for name, score in zip(names, scores): print(f"{name}: {score}")

If you need to include all elements even when lengths differ, use itertools.zip_longest() from the standard library, which fills missing values with a default.

Type Conversion and Validation Functions

Built-in functions like int(), float(), str(), bool(), list(), tuple(), set(), and dict() convert between types. They are essential for parsing input, normalizing data, and constructing collections.

python
user_input = "42" number = int(user_input) # 42 values = [1, 2, 2, 3] unique = set(values) # {1, 2, 3} pairs = [("a", 1), ("b", 2)] d = dict(pairs) # {'a': 1, 'b': 2}

bool() is particularly useful for truthiness checks. It returns False for None, False, zero, empty strings, empty collections, and objects that define __bool__() or __len__() returning false. This behavior is consistent with Python's conditional evaluation, so if some_list: is equivalent to if bool(some_list):.

int() and float() accept strings with optional whitespace and signs. int() also accepts a base parameter for converting from binary, octal, or hexadecimal strings:

python
int("0xFF", 16) # 255 int("1010", 2) # 10

When converting user input, always handle ValueError because malformed strings raise it. For robust validation, consider using str.isdigit() or regular expressions before conversion, but remember that isdigit() accepts Unicode digits that int() may not parse.

Iteration and Collection Helpers

enumerate() adds a counter to iterations, which is cleaner than manually tracking an index:

python
colors = ["red", "green", "blue"] for index, color in enumerate(colors, start=1): print(index, color)

sorted() returns a new sorted list from any iterable. It accepts key and reverse parameters. Unlike list.sort(), sorted() works on strings, tuples, dictionaries, and generators, and it does not modify the original.

python
words = ["banana", "apple", "cherry"] sorted_by_length = sorted(words, key=len) print(sorted_by_length) # ['apple', 'banana', 'cherry']

reversed() returns a reverse iterator for sequences that support __reversed__() or __len__() and __getitem__(). It works on lists, tuples, and strings, but not on sets. Dictionaries do not support reversed() directly either, even though they preserve insertion order.

range() is a built-in constructor that returns a range object, which is memory-efficient because it does not store all values. The range object behaves like an immutable sequence: it supports indexing, slicing, and membership tests, but it does not support concatenation or repetition.

Attribute and Object Management

getattr(), setattr(), and hasattr() provide dynamic access to object attributes. They are useful when attribute names come from data or configuration.

python
class User: def __init__(self, name): self.name = name user = User("Alice") attr = "name" print(getattr(user, attr)) # Alice setattr(user, attr, "Bob") print(hasattr(user, "age")) # False

getattr() accepts a default value, which avoids AttributeError:

python
age = getattr(user, "age", 30)

These functions are common in serialization frameworks, ORMs, and configuration loaders. However, overusing them can make code less explicit. Prefer direct attribute access when the attribute name is known at compile time.

callable() checks whether an object is callable. It helps when you receive a function or a method dynamically and need to verify before invoking it.

Input/Output and Environment Functions

print() and input() are the basic console I/O functions. print() accepts multiple arguments, a separator, an end string, and a file target. It flushes the output buffer when flush=True is passed, which is useful for progress indicators.

python
import sys print("Error", "occurred", sep=": ", file=sys.stderr)

input() reads a line from standard input, strips the trailing newline, and returns it as a string. It accepts an optional prompt. Always convert the result to the desired type explicitly.

open() is the built-in function for file handling. It returns a file object and supports modes like 'r', 'w', 'a', and binary variants. Using open() with a context manager (with statement) ensures the file is closed properly, even if an exception occurs.

python
with open("data.txt", "r") as f: content = f.read()

len() is a built-in that returns the number of items in a container. It works on strings, lists, tuples, dicts, sets, and any object implementing __len__(). For iterators without a known length, use sum(1 for _ in iterator).

Performance and Memory Considerations

Built-in functions are implemented in C and often avoid Python-level loop overhead, so they can be faster and more readable than hand-written loops. The difference is usually small for typical data sizes, and readability or memory behavior should guide the choice.

The bigger win is memory efficiency: map() and filter() return iterators, and range() returns a compact range object, so they avoid large intermediate lists. When processing large datasets, prefer lazy iterators over eager lists. For instance, sum(map(expensive_func, data)) computes the sum without storing all transformed values. But if you need to access items multiple times, materialize the result into a list.

Be careful with zip() if you materialize it: converting zip(names, scores) to a list stores all pairs in memory. When you only need to iterate once, the iterator itself avoids that cost. If you need random access, convert to a list of tuples.

sorted() always builds a full list in memory. For extremely large data, consider external sorting or using heapq for partial ordering.

Common Pitfalls and Edge Cases

One frequent mistake is assuming map() returns a list. In Python 3, it returns an iterator, so calling list(map(...)) is necessary if you need a list. Similarly, filter() returns an iterator.

Another pitfall is using bool() on strings. An empty string is False, but a string containing only whitespace is True. If you need to test whether a string has visible content, use if text.strip(): instead of relying on bool(text).

zip() with unequal lengths silently truncates. If that is not intended, use itertools.zip_longest() with a fill value.

getattr() with a default does not catch exceptions raised inside a property. The default is only used when the attribute does not exist. If the attribute exists but its getter raises an exception, that exception propagates.

int() accepts strings with surrounding whitespace and an optional sign. It does not accept commas as thousands separators, so remove grouping characters before converting user input.

Finally, remember that range() in Python 3 is not a list. It is an immutable sequence type: it supports indexing, slicing, and membership tests without storing all values. It does not support concatenation or repetition the way lists do.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.