Using Python’s Builtin Functions

The python interpreter has a number of builtin functions that’s available to use anytime while you’re coding. Knowing the functions available and more importantly how to use them will help make you a more efficient python programmer. To view the list of functions that’s available in the python 3 in alphabetical order read the built-in functions section of the python docs.

In this tutorial we’ll explore the functionality on what some of these functions do, and we’ll also explore what they can do. By the end of this tutorial you should have the knowledge to explore the other functions in the python docs.

abs()

The abs() function returns the absolute value of a number. Look at the function signature for details of what constitutes valid and invalid input:

abs(x)

According to pydocs, abs() returns any positive integer. Therefore we know that we can only pass numbers like integers or floating points. Examples of invalid input are strings and lists.

>>> abs(-2792.2829290)
2792.282929

The following code snippet returns an error because the argument passed is a string NOT a number.

>>> abs("hello")
Traceback (most recent call last):
  File "", line 1, in 
TypeError: bad operand type for abs(): 'str'

Quick quiz: Is the following valid input for the abs() function?

>>> abs(-True)

The answer is yes, it returns 1. With booleans True maps to 1, and False maps to 0.

all()

The all() function returns True if: one, all of the elements of the iterable are True, or two, the iterable is empty. Below are the function details:

all(iterable)

From the function signature of all() we can tell that we can only accept iterables such as a list, tuple, string, or dictionary. Things like numbers or booleans don’t qualify as valid data. Therefore, the following are valid input in the all() function in python:

>>> a = [x for x in range(1, 10) if x % 2 == 0]
>>> all(a)
True

The above would be False if instead of the list starting at 1, it starts at 0 as shown below:

>>> a = [x for x in range(10) if x % 2 == 0]
>>> all(a)
False

The reason being is because 0 maps to False, and only True elements are allowed. Therefore, if you have something like the following it would also be illegal in the all() function:

>>> truths = [True, False, True]
>>> all(truths)
False

Let’s check out a dictionary example:

>>> nums = {1: False, 2: True, 3: False, 4: True}
>>> all(nums)
True

The above evaluates to True because all of the keys are True. If you change one of the keys from 1 to 0 then the statement will evaluate to False. Below is a function that uses the all() function:

>>> def create_iterable(*nums):
...     """ create an iterable by calling function with arguments """
...     container = []
...     for x in nums:
...         container.append(x)
...     return all(container)
... 

>>> create_iterable(2, 4, 6, 7)
True
>>> create_iterable(2, 4, 6, 7, True, 1, 0.00192, 65)
True
>>> create_iterable(0, 1, 2, 6, 10, True, 542.2)
False
>>> create_iterable(True, False)
False
>>> create_iterable('hello')
True
>>> create_iterable()
True
>>> create_iterable(0.000001, 2637.292920, 9282.829)
True
>>> create_iterable(0.00, 1.2837, .54262, 98272.218)
False

bin()

The bin() builtin function converts an integer into its binary representation with the prefix of 0b.Therefore, integers are the only type allowed, numbers like floating points are not permitted. If you enter a floating point then an error will occur. Also, you don’t have to enter an integer if the object defines an __index__() which returns an integer. Some examples of this is listed below:

>>> bin(100)
'0b1100100'
>>> bin(10)
'0b1010'
>>> bin(-5)
'-0b101'
>>> bin(252.272)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'float' object cannot be interpreted as an integer
>>> bin('10100')
Traceback (most recent call last):
  File "", line 1, in rrran integer

Also, if you don’t want the output to have 0b attached to it you can modify it using the format() function in python:

>>> format(20, '#b')
'0b10100'
>>> format(20, 'b')
'10100'

Below is an example of a function that uses the bin() function. It reads in an arbitrary number of arguments and then returns it’s binary representation in dictionary format.

>>> def map_binary(*nums):
...     """ reads in binary numbers then returns binary representation """
...     output = {}
...     for x in nums:
...         output.update({x: bin(x)})
...     return output 
... 

>>> map_binary(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
{1: '0b1', 2: '0b10', 3: '0b11', 4: '0b100', 5: '0b101', 6: '0b110', 7: '0b111', 8: '0b1000', 9: '0b1001', 10: '0b1010'}

complex()

The function details for complex() is listed below:

complex([real[, imag]])

As you can see it has two parameters. The first one is any real number and the second one is it’s optional imaginary root.

>>> complex(10)
(10+0j)
>>> complex(10, 2)
(10+2j)
>>> complex(6.827)
(6.827+0j)
>>> complex(5, 7)
(5+7j)
>>> complex(-9, 20)
(-9+20j)
>>> 5 + complex(5, 10)
(10+10j)
>>> (complex(5, 5) + complex(10, 8) * complex(11, 9))
(43+183j)

Zip

The zip function combines elements from each of the iterators. The function details is listed below:

zip(*iterables)

An example of the function in action is listed below:

>>> x = [1, 2, 3, 4]
>>> y = [0, 2, 4, 6]
>>> xy = zip(x, y)
>>> list(xy)
[(1, 0), (2, 2), (3, 4), (4, 6)]

You can use an asterisk (*) operator to unpack the values of the iterables.

>>> x1, x2 =  zip(*zip(x, y))
>>> x1
(1, 2, 3, 4)
>>> x2
(0, 2, 4, 6)

The unpack function extracts every element of the iterable. Here’s another example that shows how the zip() function and unpack operator (*) work:

>>> even = [2, 4, 6, 8]
>>> odd = [1, 3, 5, 7]
>>> unpacked = [*even, *odd]
>>> unpacked
[2, 4, 6, 8, 1, 3, 5, 7]

This example is equivalent to:

>>> even + odd

You can store the unpacked values in variables as long as it matches up to the total number of output.

>>> a, b = [*even], [*odd]
>>> a
[2, 4, 6, 8]
>>> b
[1, 3, 5, 7]
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.