Python's Built-In Functions
In every previous lesson, you've used some of Python's built-in functions. The first built-in function you used was print() back in lesson 1. Since then you've used built-in functions like range(), open(), and more. Built-in functions are an invaluable part of your Python tool kit. In this lesson, we'll learn even more about them.
First we'll go over some examples that use Python built-in functions, and then explore the functions themselves.
Suppose you're throwing a party. Each invitation to your party might have 0, 1, 2, or more people attached to it. You are storing the invitations in a pair of lists. The first list holds the names of the attendees; the corresponding element in the second list is the size of the invited group. You need to know the total number of people attending in order to buy the right amount of food for the party, and for seating purposes, you need to know who has the largest group. Python's built-in functions will help you to execute both of these tasks. Start an interactive session as shown below:
>>> invites = ["Jay", "Conan", "Jimmy", "Craig"] >>> attendees = [3, 2, 0, 5] >>> sum(attendees) 10 >>> zipped = zip(attendees, invites) >>> party = tuple(zipped) >>> party ((3, 'Jay'), (2, 'Conan'), (0, 'Jimmy'), (5, 'Craig')) >>> max(party) (5, 'Craig') >>> for people, name in party: ... print(people, name) ... 3 Jay 2 Conan 0 Jimmy 5 Craig >>> for people, name in sorted(party): ... print(people, name) ... 0 Jimmy 2 Conan 3 Jay 5 Craig
Keep the console open. This example helps demonstrate a couple of new functions: sum() returns the total of all the elements in its argument; zip() interleaves (that is, alternates, like the teeth of a zipper) the elements of any number of sequences. If you call zip() with two arguments, when you loop over the result you get a sequence of two-element tuples; call it with three arguments and you get three-element tuples. zip() doesn't return a list or a tuple, but something called a generator; we called the tuple() function on it so we could see the data without needing to loop over it.
Next, using the same data, let's check to see if any or all invitations have any attendees and the total number of invitations. Type the commands below as shown:
>>> any(attendees) True >>> all(attendees) False >>> len(attendees) 4
The any() function returns True if any element of its argument is true. all() returns True if all of the elements of its argument are true. len() returns the number of elements in the argument.
The rest of this lesson provides an alphabetical reference guide to Python's built-in functions, with brief examples. As you become more familiar with Python, you'll find new and innovative ways to make use of these built-in functions.
The abs() function returns the absolute value of an integer, floating point, or complex number. The returned value is always positive. If the input value is a negative integer or floating-point number, then the absolute value is the negated argument. If the argument is complex, a positive result will still be returned, but it's a complicated calculation (the square root of the sum of the squares of the real and imaginary components). Take a look. Type the commands below as shown:
>>> abs(3.14) 3.14 >>> abs(-3.14) 3.14 >>> abs(3+4j) 5.0
The all() function returns True if all elements of the supplied iterable are true (or if there are no elements: technically, you could say it returns False if any element evaluates as false). So if all elements in a list, tuple, or set match Python's definition of being true, then all() returns True. Type the commands below as shown:
>>> lst = [1, 2, 3, 4, 5, 6]
>>> all(lst)
True
>>> lst.append('')
>>> all(lst)
False
>>> all([])
True
>>> t1 = ("Tuple")
>>> all(t1)
True
>>> t2 = ("Tuple", "")
>>> all(t2)
False
>>> s = {}
>>> all(s)
True
The any() function is the converse of the all() function. any() returns True if any element of the iterable evaluates true. If the iterable is empty, the function returns False. type the commands below as shown:
>>> lst = ["", 0, False, 0.0, None]
>>> any(lst)
False
>>> lst.append("String")
>>> any(lst)
True
>>> any([])
False
>>> any(("", 0))
False
>>> any(("", 1))
True
>>> any({})
False
>>> any({0: "zero"})
False
>>> any({"zero": 0})
True
The bool function converts the value to a Boolean, using the standard Python truth testing procedure. If x is false or omitted, it returns False; otherwise it returns True. Type the commands below as shown:
>>> bool("Python is fun!")
True
>>> t = []
>>> bool(t)
False
>>> bool(0)
False
>>> bool()
False
>>> bool(1)
True
The chr() function returns a string of one character, which has the ordinal value equal to the given integer. Type the commands below as shown:
>>> chr(90) 'Z' >>> alphabet = '' >>> for letter in range(65, 91): ... alphabet += chr(letter) ... >>> alphabet 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
dict() creates a new data dictionary with items taken from the arguments. If no arguments are passed, an empty dictionary is created. You can call dict() with a tuple or list as its argument. In those cases, each of the argument's elements must be a two-element (key, value) list or tuple. You can also use a sequence of keyword arguments. We will cover those in the lesson on functions, but in short, a keyword argument is a name followed by an equals sign and a value. Try this example:
>>> {'number': 3, 'string': 'abc', 'numbers': [3, 4, 5]}
{'number': 3, 'string': 'abc', 'numbers': [3, 4, 5]}
>>> dict([(1, "one"), [2, "two"], (3, "three")])
{1: 'one', 2: 'two', 3: 'three'}
>>> dict(zip("ABCDEF", range(10, 16)))
{'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
>>> dict(
... number=3,
... string="abc",
... numbers=[3, 4, 5]
... )
{'number': 3, 'string': 'abc', 'numbers': [3, 4, 5]}
| Modern Python | Since Python 3.7, dictionaries preserve insertion order as part of the language
specification. The original output showed {'numbers': [3, 4, 5], 'number': 3, 'string': 'abc'}
with a different key order; current Python returns the keys in the order they were inserted. |
The dir() function can accept any argument: string, integer, dictionary, function, class, or method. Without arguments, dir() returns the list of names in the current local scope. If an argument is given, then the result is a list of the names in the namespace of the given object. The list returned is always sorted in alphabetical order. Type the commands below as shown:
>>> p = 'Python' >>> dir(p) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
| Note | The list above was produced on current Python and is longer than the original.
New methods like casefold(), format_map(), isascii(),
removeprefix(), and removesuffix() have been added to strings since
Python 3.1. Private helpers such as _formatter_field_name_split were removed. |
The globals() function returns a dictionary representing the current global symbol table. This is always the namespace dictionary of the current module. Type the commands below as shown:
>>> list(globals().items())
[('__name__', '__main__'), ('__doc__', None), ('__package__', None),
('__loader__', <class '_frozen_importlib.BuiltinImporter'>),
('__spec__', None), ('__builtins__', <module 'builtins' (built-in)>)]
>>> first = "Hello"
>>> second = "Goodbye"
>>> list(globals().items())
[('__name__', '__main__'), ('__doc__', None), ('__package__', None),
('__loader__', <class '_frozen_importlib.BuiltinImporter'>),
('__spec__', None), ('__builtins__', <module 'builtins' (built-in)>),
('first', 'Hello'), ('second', 'Goodbye')]
| Note | If you see more keys listed than are displayed in this example, it's probably because you've been trying different snippets of code. |
| Modern Python | Current Python adds __loader__ and __spec__ to the
global namespace, and preserves insertion order. The original output showed a different (and
shorter) set of keys in an unspecified order. |
The help() function is your new best friend. Call help() with any object as its argument to see usage information on the object (if the programmer has provided it). For experienced Python programmers, this is the first tool to use when trying to figure out something they don't understand. Once you start writing more advanced Python programs, you'll learn how to write your own help text.
In an interactive Python console, use the help(object) function on any variable, string, integer, list, tuple, set, or built-in function, including the help() function. Some of the text won't make sense to you right now, but you'll still find this function very useful. To scroll through larger help documents, press the space bar. To exit, press q. Type the commands as shown:
>>> help(globals)
Help on built-in function globals in module builtins:
globals()
Return the dictionary containing the current scope's global variables.
NOTE: Updates to this dictionary *will* affect name lookups in the current
global scope and vice-versa.
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
>>>
Once you have opened the help context you can leave it simply by pressing the q key.
len(s) returns the length of an object. The argument provided may be a sequence (string, tuple, or list) or a mapping (dictionary). Type in these commands:
>>> s = "Python"
>>> len(s)
6
>>> lst = [1, 2, 3]
>>> len(lst)
3
>>> d = {"a":"b", "c":"d", "e":"f"}
>>> len(d)
3
The locals() function returns a dictionary representing the current local symbol table. Unless it's called inside a function, it will return the same list as globals(). Type in this command:
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
| Note | Just like the globals() function, you will likely see more keys than we show in this example. That's perfectly fine; what you see reflects what you did in the session. If you've been testing different snippets of code, good for you! |
The max() function, with a single argument iterable, returns the largest item of a non-empty iterable (such as a string, tuple, or list). With more than one argument, it returns the largest of the arguments. Type these commands:
>>> lst1 = [16, 32, 8, 64, 2, 4] >>> max(lst1) 64 >>> lst2 = ['one', 'two', 'three', 'One', 'Two', 'Three'] >>> max(lst2) 'two' >>> max(42, 76, -104) 76 >>> max(1, 2, "three") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'str' and 'int'
Don't close the session—we'll use lst1 and lst2 later! The first result is 64. The second result of 'two' might have surprised you, but Python compares strings "lexicographically" (the way they would be sorted for a dictionary, but with all the lower-case letters greater than any upper-case one), not by the meaning of the words. The last expression caused an error, because you can't compare strings and integers: they are fundamentally different types.
| Modern Python | The TypeError message has changed. Python 3.1 said
unorderable types: str() > int(); current Python says
'>' not supported between instances of 'str' and 'int', which is
more specific about the operation that failed. |
The opposite of the max() function, min(iterable) returns the smallest item of a non-empty iterable (such as a string, tuple, or list). With more than one argument, it returns the smallest of the arguments. Type these commands:
>>> min(lst1) 2 >>> min(lst2) 'One' >>> min(42, 76, -104) -104 >>> min(1, 2, 'three') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'str' and 'int'
The first result is 2. The second result of 'One' seems to make sense, but be aware that Python returned the lowest value of an alphanumeric sort, "O" being less than "T": Python neither knows nor cares about the meaning of the words. The fourth expression raised an exception here as well, because you can't compare strings and integers.
ord(c) is the inverse of the chr() function we discussed earlier. Given a string of length one, it returns an integer representing the ordinal value of the character. For example, ord('A') returns the integer 65. Type these commands:
>>> alphabet = 'ABCDEFGH' >>> for letter in alphabet: ... print(ord(letter), letter) ... 65 A 66 B 67 C 68 D 69 E 70 F 71 G 72 H
pow(x, y[, z]) returns x to the power y. If a third argument z is given, then the result is reduced modulo z (then you get the remainder after dividing (x raised to the power y) by z).
You might have played with a calculator at one time or another, using repeated multiplication to raise a number to successive powers. In the next example, Python automates the calculations for you. Type these commands:
>>> pow(2, 2) 4 >>> pow(2, 3) 8 >>> pow(2, 4) 16 >>> for i in range(5, 12): ... print(pow(2, i), pow(2, i, 100)) ... 32 32 64 64 128 28 256 56 512 12 1024 24 2048 48
sorted(iterable) returns a new sorted list from the items in iterable. This arranges your lists, tuples, and sets in a known order. Type these commands:
>>> numbers = [3, 1, 6, 7, 1100, 10] >>> sorted(numbers) [1, 3, 6, 7, 10, 1100] >>> t = ['Beta','beta','alpha','Alpha'] >>> sorted(t) ['Alpha', 'Beta', 'alpha', 'beta'] >>> lst2 = ['one', 'two', 'three', 'One', 'Two', 'Three'] >>> sorted(lst2) ['One', 'Three', 'Two', 'one', 'three', 'two']
The first sorted list provides an expected result. The second list you may not have anticipated. Python sorts in alphanumeric order, but all upper-case letters sort lower than all lower-case letters.
You can also use keyword arguments to specify how the sort keys should be created, and whether to sort in ascending or descending order. Suppose you want to have a case-insensitive search. You can do this by using a function as the key argument of the sort. In this case, you use the Python string type's lower-case method. In the second example, you request a descending sort with the reverse keyword argument. Type these commands:
>>> t = ['Beta','beta','alpha','Alpha'] >>> sorted(t, key=str.lower) ['alpha', 'Alpha', 'Beta', 'beta']
| Note | When you use the lower() function on otherwise identical strings like 'Beta' and 'beta', Python treats them as identical, keeping them in the same order they were input, so 'beta' might not appear before 'Beta' when you try the above example. |
>>> t = ['Bete','beta','alphie','Alpha'] >>> sorted(t, key=str.lower) ['Alpha', 'alphie', 'beta', 'Bete'] >>> sorted(t, reverse=True) ['beta', 'alphie', 'Bete', 'Alpha']
reversed(seq) is a reverse iterator on an object of the type that you can loop through and process. The list and tuple types are supported with this function, but the set type is not (because the elements of a set aren't ordered). Type these commands:
>>> lst = [1, 2, 3] >>> reversed(lst) <list_reverseiterator object at 0x...> >>> for i in reversed(lst): ... print(i) ... 3 2 1
| Note | The memory address shown after 0x will differ on your machine.
The source had a typo (>>> instead of ... on the loop body
line); the corrected prompt is shown here. |
The round(x[, n]) function rounds the decimal value x to the nearest integer. If you give a second argument n, it rounds to that number of decimal places. Type these commands:
>>> round(33.5) 34 >>> round(33.3333333333, 2) 33.33
| Modern Python | Python uses round-half-to-even (banker's rounding): when a value is
exactly halfway between two integers it rounds to the nearest even integer.
So round(0.5) is 0 and round(34.5) is
34, not 35. round(33.5) gives 34
because 34 is even. This behaviour has been present since Python 3.0. |
sum(iterable) sums the numeric values in an iterable such as a list, tuple, or set. sum(iterable) does not work with strings because you can't do math on strings (when you add two strings you are really using an operation called concatenation). Type these commands:
>>> s = {1, 2, 3}
>>> sum(s)
6
>>> lst = ['Python','is','fun']
>>> sum(lst)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
So we are able to add up numbers, but things break down on letters and words. To combine strings in a list, rely on the string join() method as shown below:
>>> lst = ['Python','is','fun!'] >>> ' '.join(lst) 'Python is fun!'
The zip() function takes iterables and aggregates elements from each of the iterables into a new iterable object. That might sound complicated, but the example below will help illustrate the concept. Type these commands:
>>> lst_1 = ['Python','is','fun']
>>> lst_2 = [1000, 2000, 3000]
>>> lst_3 = [10, 9, 8, 7, 6, 5]
>>> list(zip(lst_1, lst_2))
[('Python', 1000), ('is', 2000), ('fun', 3000)]
>>> list(zip(lst_1, lst_2, lst_3))
[('Python', 1000, 10), ('is', 2000, 9), ('fun', 3000, 8)]
In the first result, we used the list() function to create a list of three tuples. The second example is not so clear, as we are missing the last two elements of lst_3. That's because the zip function ignored iterations for which it didn't have elements in all of the supplied iterables. This enables us to create dicts using the zip() function. Try it out:
>>> lst_1 = ['Python','is','fun']
>>> lst_3 = [10, 9, 8, 7, 6, 5]
>>> d = {}
>>> for k, v in zip(lst_1, lst_3):
... d[k] = v
...
>>> d
{'Python': 10, 'is': 9, 'fun': 8}
>>> zip((1, 2), (3, 4))
<zip object at 0x...>
zip() returned a generator called a "zip object."
| Modern Python | zip(), map(), and filter() all return
lazy iterator objects rather than lists—the object prints as
<zip object at 0x...>. Wrap the call in list() when you need
to see all the values at once, as shown in the examples above. |
You've worked with lots of different functions in this lesson, and used them to get a real idea of how they work.
Keep your interpreter window open to test your understanding of new functions as you come into contact with them. Experiment and try to find their limits. Use the help() function to learn more about the built-in functions too.
You're looking good so far. Keep up the great work!
