Commonly Used Python Built In Functions

Commonly Used Python Built In Functions

Python is known for its batteries-included philosophy. You have access to all kinds of very powerful tools by using the rich libraries and modules available. Python also has many built-in functions that do not require you to import them before using them. There are well over 50 included, but we’ll take a look at some of the more commonly used built-in functions in this tutorial. We’ll take a look at python functions such as len(), range(), list(), min(), max(), round(), abs(), pow(), sorted(), split(), type(), and isinstance(). These functions are going to be useful to you no matter what type of application you are trying to build.


len()

len and strings

The first function we want to look at is the len() function. It takes one input and it outputs a whole number representing the length of the input provided. This is generally a list, but can also be a string or dictionary. We can start with a meat variable that holds the string ‘Bacon’. We can use the len() function to count how many characters are in a string.

Bacon has 5 characters

Let’s try this exercise again on a vegetable. Now we have a variable named veggie and we store the string of ‘Broccoli’ in it. By again using that len() function, we are able to calculate how many characters are in the string ‘Broccoli’.

Broccoli has 8 characters

len and lists

Using the len function with lists is super common. To demonstrate this one, we’ll just create a ticker variable and store a list of stock tickers inside of it. Once again by applying the len() function we see that there are 4 tickers in the list.

There are 4 tickers in the list

The len function is also commonly used for looping. This is because you can use len to set the upper range of the loop. In other words, as long as the current iteration is smaller than the length of the list, you can keep looping. Here is an example where we loop through the length of our list and print out each ticker.

lk
msft
bynd
crc

A list of integers is also easy to calculate the length for.

7

Now we look at dictionaries and the len function. Dictionaries have key value pairs as we have learned. When using len() with dictionaries, it counts the number of key value pairs contained in the dictionary. It does not count each key, and each value as unique. Here we create a dictionary that contains stock tickers and their associated prices. We use the len function to look at the length.

There are 3 tickers in the dictionary

Lastly, since lists can store a mix of all different types, we can put some of these various lists we’ve been working on inside of a list themselves, and use the len function again.

There are 5 items in the mixed list

range() and list()

The range() function is one of the most used functions in Python. It is very versatile and can be used in many ways. The first way to use the range() function is to simply pass it one whole number as an input. So we’ll create a variable named team_members and use range to fill that variable.

The output above is interesting. If we print out the variable directly, it shows range(0, 25), but when use the len function on the variable, we see there are in fact 25 members. It’s important to note that the range fuction counts from 0 up to 1 less than the upper range. So if we where to output the contents of team_members, we would see 0-24, and not 1-25.

With that in mind, we can now look at the list() function. It takes a tuple as an input and outputs a list having the same data as the tuple. So we go from an immutable collection of data to a mutable collection of data by using the list() function. We can use list() to list out the members in our range instance. Let’s see.

We can use list() in the context of a for loop like so.

Player 0
Player 1
Player 2
Player 3
Player 4
Player 5
Player 6
Player 7
Player 8
Player 9
Player 10
Player 11
Player 12
Player 13
Player 14
Player 15
Player 16
Player 17
Player 18
Player 19
Player 20
Player 21
Player 22
Player 23
Player 24

Now we can see how the list() function is useful for us. Below we split up our range of players into a Team A or a Team B. We are able to do this by popping player off on each iteration and placing them in either Team A or Team B based on whether their number is even or odd. If we did not use the list() function, we would get an error like “AttributeError: ‘range’ object has no attribute ‘pop'”.

Player 0 is on team A
Player 2 is on team A
Player 4 is on team A
Player 6 is on team A
Player 8 is on team A
Player 10 is on team A
Player 12 is on team A
Player 14 is on team A
Player 16 is on team A
Player 18 is on team A
Player 20 is on team A
Player 22 is on team A
Player 24 is on team A
Player 1 is on team B
Player 3 is on team B
Player 5 is on team B
Player 7 is on team B
Player 9 is on team B
Player 11 is on team B
Player 13 is on team B
Player 15 is on team B
Player 17 is on team B
Player 19 is on team B
Player 21 is on team B
Player 23 is on team B

min() and max()

Now lets look at the min and max functions in Python. They do exactly what you think they would do, which is to find the lowest or highest values in a collection. For the first test, we’ll just use a range of numbers to demonstrate min and max. We can see that negative integers are taken into account when using min or max.

5
-5

Now we are going to go shopping. We are looking at some jeans, a sweater, and a pair of shoes. The cost 40, 50, and 100 respectively.

Now we want to see what is the highest and lowest cost.

40
100

These functions work on strings as well. Maybe during the shopping expedition, we visited Kohls, Target, Bed Bath and Beyond, Best Buy, and Applebees. The example below shows that min and max calculate based on the alphabet, not on the length of the string.

Kohls
Applebees

Now we also look at a tshirt which is 15 dollars, and we again use the min and max functions to look at the lowest and highest prices.

15
100

round() abs() and pow()

Python has the round(), abs(), and pow() functions built-in. You can use these to round a number, get the absolute value of a number, or set a number to an exponent quite easily. We can start with a frappuccino. Consider you just spent $4.72 on one of these. We can use the round function to see a round number of that cost.

5

round() takes an optional second parameter which specifies the number of decimal places to round to.

3.1416

The abs() function gives us the ability to find the absolute value of a number. Many times you’ll want the absolute value of a negative number. Here are a few examples of abs() in action.

Absolute value of -7 is: 7
Absolute value of -2.75 is: 2.75
2.5

Python also has the pow() function for raising a number to a power.

1024

sorted()

We can sort data with the sorted() function in Python. The sorted function takes an iterable, which is just something we can iterate over. This means things like lists, tuples, strings, dictionaries, and so on. The sorted function then outputs a list with the items from the input sorted. Let’s start with a simple sort of some numbers.

[-54, -7, 12, 15, 32, 44]

We can reverse the sort order with an optional second parameter.

[44, 32, 15, 12, -7, -54]

If we have a list of strings, the sorted function will sort them alphabetically.

['Best Buy', 'Costco', 'Kohls', 'Target', 'Walmart']
['Walmart', 'Target', 'Kohls', 'Costco', 'Best Buy']

Sorting Key-Value Pairs in Dicts

You can do some really interesting sorting techniques on dictionaries by making use of the optional parameters. Here we have a dictionary of key-value pairs.

First, we want to sort this by keys like so.

Apple 318.38
Cisco 49.06
Google 1487.64
Microsoft 165.27

Now we want to sort the dictionary by values.

Cisco 49.06
Microsoft 165.27
Apple 318.38
Google 1487.64

We can add the reverse parameter to these as well.

Microsoft 165.27
Google 1487.64
Cisco 49.06
Apple 318.38

Google 1487.64
Apple 318.38
Microsoft 165.27
Cisco 49.06

Sorting Tuples

It’s possible to store several tuples inside of a list. Consider we have a shirts variable, and inside of it are 4 shirts. Each is represented by a tuple. Each tuple has 3 values that represent the color, size, and price of the shirt.

We can sort by the 1st, 2nd, or 3rd position of the tuple.

[('Blue', 'XL', 25), ('Green', 'S', 10), ('Red', 'L', 15), ('Yellow', 'M', 20)]

[('Red', 'L', 15), ('Yellow', 'M', 20), ('Green', 'S', 10), ('Blue', 'XL', 25)]

[('Green', 'S', 10), ('Red', 'L', 15), ('Yellow', 'M', 20), ('Blue', 'XL', 25)]

type() and isinstance()

It helps to know what you’re working with when programming. That is where the type functions come into play. The type() function takes one input and the output is the type of the given input. This could be a string, int, or any valid object. Here are a few examples of how this works in code.

<class 'range'>

<class 'int'>

<class 'str'>

<class 'str'>

So by the examples above, you get an idea of how type() works. Now we want to see how the isinstance() function works. We need to provide a couple of simple classes to see this in action.

<class '__main__.Car'>

<class '__main__.Car'>

<class '__main__.Truck'>

False
True

True
True

All of the built-in Python functions can be found in this table.

Python Built-in Functions

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

dir()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

Commonly Used Python Built-In Functions Summary

In this tutorial, we covered a lot of ground with many of the Python built-in functions. Test them out on your own, try them in your own code, and see what they can do for you. You’ll find that you’re able to complete many of the more common tasks you are trying to accomplish with these built-in functions.