Built-in Functions
Python's built-in functions are available everywhere — no import. The list is small enough to learn but powerful enough that most Python you write uses several.
Sequences & iterables
| Function | Returns |
|---|---|
len(x) | Length. |
min(iter) / max(iter) | Smallest / largest. |
sum(iter) | Total. |
sorted(iter, key=, reverse=) | New sorted list. |
reversed(iter) | Reverse iterator. |
enumerate(iter, start=) | (index, value) pairs. |
zip(*iters) | Pair up. |
map(fn, iter) / filter(fn, iter) | Transform / filter. |
any(iter) / all(iter) | True if any / all truthy. |
range(stop) | Integer iterator. |
Type / conversion
| Function | Returns |
|---|---|
type(x) / isinstance(x, T) | Type info. |
int / float / str / bool | Cast. |
list / tuple / set / dict / frozenset | Build a collection. |
bytes / bytearray | Binary. |
hash(x) | Hashable value's hash. |
I/O
| Function | Returns |
|---|---|
print(*args, sep=, end=, file=) | Print to stdout. |
input(prompt) | Line from stdin. |
open(path, mode, encoding=) | File handle. |
Reflection / introspection
| Function | Returns |
|---|---|
dir(x) | Names attached to x. |
vars(x) / x.__dict__ | Attribute dict. |
getattr(x, name, default) | Get an attribute. |
setattr(x, name, value) | Set one. |
hasattr(x, name) | True if defined. |
help(x) | Docstring viewer. |
Math
| Function | Returns |
|---|---|
abs / round / pow / divmod | Number ops. |
bin / oct / hex | String in base 2 / 8 / 16. |
chr / ord | int ↔ Unicode codepoint. |
Tip: If you find yourself writing a small loop with an accumulator, there's probably a built-in for it. Check
sum, any, all, min, max, sorted first.Example
Example
# Common built-ins:
print(len('abc'))
print(sum([1, 2, 3]))
print(sorted([3, 1, 2]))
print(list(map(str.upper, ['a', 'b'])))
print(any([False, True]), all([True, True]))
Try it Yourself »
Exercise
Return total of an iterable of numbers.
([1, 2, 3])
Three letters.
Discussion
Loading…