This is an archived version of the course. Please see the latest version of the course.

Built-in functions

Python provides many useful built-in functions. A complete list of built-in Python functions is available here, although some of these are actually classes (e.g. range, int, str, float, enumerate). These will be prepended by the keyword class in the documentation.

We have already seen a few of these functions, like len(), print(), isinstance(), id().

Python provides some built-in Mathematical functions:

>>> print(sum([2, 3]))
>>> print(min([4, 1, 7]))
>>> print(max([4, 1, 7]))
>>> print(abs(-4))           # absolute value
>>> print(pow(2, 4))         # 2 to the power of 4
>>> print(round(5.6))        # round to nearest integer 
>>> print(round(5.678, 2))   # round to nearest 2d.p.

You might also find any() and all() quite useful!

>>> all_true = all([True, True, True, True])
>>> print(all_true)
True
>>> all_true = all([True, False, True, True])
>>> print(all_true)
False
>>> any_true = any([True, False, True, True])
>>> print(any_true)
True

You can use the sorted() and reversed() functions to return a sorted/reversed sequence.

>>> numbers = [1, 5, 3, 7, 8, 2]
>>> sorted_numbers = sorted(numbers)
>>> print(sorted_numbers)
[1, 2, 3, 5, 7, 8]
>>> reversed_numbers = reversed(numbers)  # reversed returns an `iterator`.
>>> print(list(reversed_numbers))  # you will need to convert it to a list if you need a list
[2, 8, 7, 3, 5, 1]

Remember that everything is an object in Python, and so are functions!

>>> print(type(len))
<class 'builtin_function_or_method'>
>>> print(type(print))
<class 'builtin_function_or_method'>

This means that you can assign functions to a variable, whether it is your own function or a built-in function. Sort of like a function pointer in C++, but without having to deal with pointers.

>>> my_len = len
>>> print(type(my_len))
>>> print(my_len([1, 2, 3]))
3