iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FunctionReturns
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

FunctionReturns
type(x) / isinstance(x, T)Type info.
int / float / str / boolCast.
list / tuple / set / dict / frozensetBuild a collection.
bytes / bytearrayBinary.
hash(x)Hashable value's hash.

I/O

FunctionReturns
print(*args, sep=, end=, file=)Print to stdout.
input(prompt)Line from stdin.
open(path, mode, encoding=)File handle.

Reflection / introspection

FunctionReturns
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

FunctionReturns
abs / round / pow / divmodNumber ops.
bin / oct / hexString in base 2 / 8 / 16.
chr / ordint ↔ 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])

Test yourself

Q1. For (i, v) pairs while iterating use…
Q2. For new sorted list use…
Q3. For "if at least one truthy" use…

Discussion

Loading…