Python for Programmers: Built-in Functions
Welcome to the Built-in Functions lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Python comes with "batteries included", which means that its standard library is larger than many other languages'. Much of that functionality is inside of modules that we can import. However, some of it is available in the global namespace as "built-ins".
We've already seen one built-in function,
len. This lesson covers some other useful built-ins.There are a few mathematical built-in functions.
sumadds all values in an iterable together.>
sum([1, 2, 3, 4])Result:
10
Calling
sumon an empty iterable returns 0.>
sum([])Result:
0
The
sumfunction takes an optionalstartargument, which has a default value of 0. This is the initial value for the internal counter used when summing the values.>
sum([1, 2, 3], start=4)Result:
10
If the list is empty, its sum (0) is added to the initial value.
>
sum([], 6)Result:
6
sumis primarily intended for numeric types. However, it also works with other data types that support the+operator. In those cases, we need to provide a properstartvalue.>
# This is equivalent to `[1, 2] + [3, 4] + [5, 6]`.sum([[1, 2], [3, 4], [5, 6]], start=[])Result:
[1, 2, 3, 4, 5, 6]
If we remove the
startargument in that code, we get an error. The problem is thatstartdefaults to 0. Trying to add 0 to a list is an error.>
sum([[1, 2], [3, 4], [5, 6]])Result:
TypeError: unsupported operand type(s) for +: 'int' and 'list'
It seems like
sumshould also work with strings, likesum(["a", "b"], start="").However, that doesn't work. Python even has a specific error message saying why. Check the error message below. Python really does not want us to sum strings like this!>
sum(["a", "b"], "")Result:
TypeError: sum() can't sum strings [use ''.join(seq) instead]
Calling
min(data)returns the smallest element in the iterable, whilemaxreturns the biggest.>
# Passing lists to `min` and `max`.data = [3, 5, 9, 7, 2](min(data), max(data))Result:
(2, 9)
minandmaxare both flexible with their arguments. We can pass a single iterable, as shown above. Or we can pass individual values as separate arguments. In that case, we get the smallest (or largest) of the arguments.>
# Passing individual arguments to `min` and `max`.(min(5, 2, 7), max(3, 8, 10))Result:
(2, 10)
Calling
minormaxwithout elements raises aValueErrorexception.>
max([])Result:
ValueError: max() iterable argument is empty
Unlike
sum, theminandmaxfunctions work with strings. For example,"a" < "b" < "c" < ... < "z". If the first characters of each string differ, the word with the "greater" letter is bigger. If the first characters are the same, Python compares the second characters, then the third, etc. This is called comparing in "lexicographic order".>
min("sword", "shield", "potion")Result:
'potion'
>
min("abr", "abd", "aca")Result:
'abd'
Lists have a
.sortmethod, which sorts the list. It changes the original list, which is OK in some situations. But we often want a sorted copy of a list without changing the original.The
sortedbuilt-in takes any iterable, sorts it, and returns the sorted values as a list. Unlike.sort,sorteddoesn't change the original iterable.>
data = [3, 2, 1, 4]sorted_data = sorted(data)(data[0], sorted_data[0])Result:
(3, 1)
Strings are iterable, so we can pass them to
sorted. We get back a list of letters sorted fromatoz.sortedalways returns a list, regardless of the iterable we pass it.>
my_word = "cat"sorted_letters = sorted(my_word)sorted_lettersResult:
['a', 'c', 't']
Like
.sort,sortedtakes an optionalreversekeyword argument. This flips the usual sorting order. For example, numbers are normally sorted from smallest to largest.>
data = [2, 1, 3]sorted_data = sorted(data)sorted_dataResult:
[1, 2, 3]
>
data = [2, 1, 3]sorted_data = sorted(data, reverse=True)sorted_dataResult:
[3, 2, 1]
sortedalso takes an optionalkeyargument. The key must be a function, whichsortedcalls on each iterable value. Then it sorts the values according to the function's return values. In the next example, we use it to sort cats by their ages.>
cats = [{"name": "Wilford","age": 17}, {"name": "Keanu","age": 2}, {"name": "Ms. Fluff","age": 4}]sorted_by_age = sorted(cats, key=lambda cat: cat["age"])sorted_by_age[0]["name"]Result:
'Keanu'
>
words = ["win", "surrender", "draw"]sorted_by_length = sorted(words, key=lambda word: len(word))sorted_by_length[0]Result:
'win'