Built-in Functions in Python: A Beginner's Guide
Part of the series Python Basics — part 4
A built-in function is a function that Python gives you from the very first line of your program. You don’t have to install anything or write import. You have already used several of them: print(), input(), int() and len().
In this blog, we’ll go through Python’s built-in functions one by one, grouped by what they are used for. For each function, you’ll find:
- a plain explanation of what it does,
- an example, with the output and an explanation of how that output comes about,
- and where the function is used in real programs.
Functions, classes and what Python calls them
A function is called by writing its name followed by brackets. The values you put inside the brackets are called arguments. They are the information you hand to the function so that it can do its job:
print(len("hello"))
Output:
5
Here, len is the function, and "hello" is the argument. The function counts the characters and gives back 5. The value that a function gives back is called its return value.
Many of the “functions” in this list, such as int(), str(), list() and dict(), are actually classes (types). You call them with brackets in exactly the same way, so for everyday use the difference doesn’t matter. That is why type(5) shows <class 'int'>: int is a class. You can see this in Data Types in Python.
All the examples in this blog were run with Python 3.14.
All the built-in functions at a glance
| Group | Functions |
|---|---|
| Input and output | print(), input(), help() |
| Creating and converting values | int(), float(), complex(), str(), bool(), list(), tuple(), set(), frozenset(), dict(), bytes(), bytearray(), memoryview(), range() |
| Checking types | type(), isinstance(), issubclass(), callable() |
| Numbers | abs(), round(), pow(), divmod(), min(), max(), sum(), bin(), oct(), hex() |
| Characters and text | chr(), ord(), ascii(), repr(), format() |
| Working with collections | len(), sorted(), reversed(), enumerate(), zip(), map(), filter(), all(), any(), slice(), iter(), next(), aiter(), anext() |
| Objects and classes | object(), id(), hash(), dir(), vars(), getattr(), setattr(), hasattr(), delattr(), property(), classmethod(), staticmethod(), super() |
| Running code and files | eval(), exec(), compile(), globals(), locals(), breakpoint(), open() |
Input and output
print()
The print() function displays values on the screen. It is how a program talks to the person using it: you can print a message, the result of a calculation, or the value stored in a variable.
You can put several values inside the brackets, separated by commas. print() shows them on one line, with a space between them. Two optional settings change this:
sep(short for separator) is what goes between the values. The default is a single space.endis what goes after the last value. The default is a line break, which is why eachprint()normally starts on a new line.
print("Hello", "World")
print("Hello", "World", sep=", ")
print("Loading", end="...")
print("done")
Output:
Hello World
Hello, World
Loading...done
In the first line, the space comes from the default sep. In the second, we replaced it with a comma and a space. In the third, end="..." replaces the line break, so the next print() continues on the same line, which is why done appears right after the three dots.
To break a line or add a paragraph break inside a text, use \n for a new line and \n\n for a blank line between two paragraphs:
print("First paragraph.\n\nSecond paragraph.")
Output:
First paragraph.
Second paragraph.
See Python Coding Exercise #05 for more about how print() handles spaces.
input()
The input() function is used when the program needs information from the user. It works in three steps:
- It shows the message you gave it, called the prompt.
- It waits while the user types and presses Enter.
- It returns what the user typed, so you can store it in a variable and use it later.
The result is always a string, even when the user types a number.
name = input("What is your name? ")
print("Hello,", name)
Output:
What is your name? Anna
Hello, Anna
The first line of the output is the prompt followed by what the user typed (Anna). The second line comes from print(), which uses the stored name.
Because the answer is always text, you need to convert it before you can calculate with it. The usual way is to wrap input() in int() or float():
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
Output:
How old are you? 30
Next year you will be 31
See Python Coding Exercise #08 for more about converting input.
Where it’s used: Any program that asks the user something: forms, quizzes, calculators, games, etc.
help()
The help() function is the quickest way to learn more about a function, a method or a module without leaving Python. Give it the name of the thing you want to know about, and it displays the documentation:
help(len)
It displays what the len function does:
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
The second line shows how the function is called (len(obj, /): it takes one value), and the third line describes what it does.
Where it’s used: When you can’t remember what a function does or which arguments it takes. It also works with your own functions, if you write a short description inside them.
Creating and converting values
Computers treat the text "5" and the number 5 as two different things. You can add numbers together, but you can’t add text in the same way. The functions in this group create a value of a certain type, or convert a value from one type to another. Converting a value is often called type casting, as in Python Coding Exercise #31.
int()
The int() function converts a value to an integer, which is a whole number without decimal. It accepts a string that contains a whole number, or a decimal number.
print(int("42"))
print(int(3.9))
print(int(-3.9))
Output:
42
3
-3
int("42")turns the text"42"into the number42.int(3.9)gives3.int()does not round. It cuts off everything after the decimal point.int(-3.9)gives-3, because cutting off the decimals moves the number towards zero.
Reading numbers written in another number system. int() has an optional second argument called the base. By default, the base is 10, the number system we use every day, with the digits 0 to 9. If the text is written in a different number system, the base tells Python which one.
print(int("101", 2))
Output:
5
Why does this print 5? The 2 is the base, and it tells Python: “this text is written in binary” (base 2). Binary uses only the digits 0 and 1. In a binary number, each position has a value that doubles as you move to the left: 1, 2, 4, 8, and so on. For 101:
| Digit | 1 | 0 | 1 |
|---|---|---|---|
| Position value | 4 | 2 | 1 |
| Digit × value | 1 × 4 = 4 | 0 × 2 = 0 | 1 × 1 = 1 |
Add them up: 4 + 0 + 1 = 5. So int("101", 2) means “read 101 as a binary number, and give me the ordinary number”.
The same idea works for other bases. In base 16 (hexadecimal), the letters a to f stand for 10 to 15, and in base 8 (octal), the digits go from 0 to 7:
print(int("1010", 2))
print(int("ff", 16))
print(int("17", 8))
Output:
10
255
15
ff in base 16 is 15 × 16 + 15 = 255, and 17 in base 8 is 1 × 8 + 7 = 15. The functions bin(), oct() and hex(), later in this blog, go the other way round, from a number to text in these systems. See also Python Coding Exercise #24.
When int() can’t convert. If the text isn’t a whole number, Python stops with an error. This includes text with a decimal point, like "3.5":
print(int("3.5"))
Output:
ValueError: invalid literal for int() with base 10: '3.5'
To convert such text, first turn it into a decimal number with float(), and then into an integer:
print(int(float("3.5")))
Output:
3
Where it’s used: Converting what the user types with input() into a number, reading numbers from files or spreadsheets (where everything starts as text), and turning measurements into whole numbers, such as a count of items or an age.
float()
The float() function converts a value to a float, which is a number with a decimal part. It accepts a string that contains a number, or a whole number.
print(float("3.5"))
print(float(7))
Output:
3.5
7.0
float("3.5") turns the text into the decimal number 3.5. float(7) turns the whole number 7 into 7.0. The .0 shows that Python now treats it as a decimal number.
complex()
The complex() function creates a complex number, a number made of a real part and an imaginary part. In Python, the imaginary part is written with a j. You give it the two parts, and you can read them back with .real and .imag.
z = complex(2, 3)
print(z)
print(z.real, z.imag)
print(z * complex(1, 1))
Output:
(2+3j)
2.0 3.0
(-1+5j)
complex(2, 3) creates 2 + 3j. The last line multiplies it by 1 + 1j, and Python follows the rules of complex numbers to give -1 + 5j.
Where it’s used: Engineering, physics and signal processing, where complex numbers are part of the formulas.
str()
The str() function converts a value to a string, which means text. You can give it a number, a list, True and almost anything else, and it gives back the same value written as text.
print(str(42))
print(type(str(42)))
print(str(3.14))
print(str(True))
print(str([1, 2, 3]))
Output:
42
<class 'str'>
3.14
True
[1, 2, 3]
str(42) looks the same as 42 on the screen, but it is now the text "42", and type() confirms it is a string.
Why is this useful? The + operator joins two pieces of text, but it can’t join text and a number. If you try, Python stops with an error:
print("I have " + 5 + " apples")
Output:
TypeError: can only concatenate str (not "int") to str
The error says Python can only join a string to another string, and 5 is an integer. The fix is to convert the number to text first with str():
print("I have " + str(5) + " apples")
Output:
I have 5 apples
Now all three pieces are text, and + joins them into one sentence. (An f-string, such as f"I have {5} apples", does the conversion for you.)
Where it’s used: Building messages that mix text and numbers, counting the digits of a number with len(str(number)), and preparing numbers to be written into a text file.
bool()
The bool() function converts a value to a Boolean, which is either True or False. Python decides using one rule: some values count as “empty” and become False, and everything else becomes True.
The values that become False are 0, 0.0, an empty string "", an empty list [], an empty dictionary {} and None.
print(bool(0), bool(5))
print(bool(""), bool("hello"))
print(bool([]), bool([0]))
Output:
False True
False True
False True
In each line, the first value is “empty” and the second one is not. Notice the last pair: [0] is a list that contains one item (the number zero), so the list is not empty, and bool([0]) is True. The string "False" also gives True, because it is a string with characters in it.
Where it’s used: Checking whether something has a value, such as whether the user typed an answer, or whether a list has any items. This is what an if statement does behind the scenes when you write if name:.
list()
The list() function creates a list, or converts another collection into a list. A list is an ordered collection of items that you can change. Giving it a string splits the string into a list of its characters, and giving it a range() turns the numbers into a list.
print(list("abc"))
print(list(range(3)))
print(list())
Output:
['a', 'b', 'c']
[0, 1, 2]
[]
list("abc") gives a list with three items, one for each character. list(range(3)) gives the numbers 0, 1 and 2 in a list. list() with nothing inside the brackets gives an empty list.
Where it’s used: Turning the result of functions like range(), map(), zip() and filter() into a list so you can see and use the items, and splitting a word into its letters.
tuple()
The tuple() function creates a tuple, or converts another collection into one. A tuple looks like a list, but once it is created, it can’t be changed.
point = tuple([4, 7])
print(point)
print(point[0])
Output:
(4, 7)
4
The list [4, 7] becomes the tuple (4, 7). You can read the items by their position, like point[0], but you can’t change them.
Where it’s used: Data that should stay fixed, such as coordinates or colour values (red, green, blue), and functions that return several values at once.
set()
The set() function creates a set, or converts another collection into one. A set keeps only one copy of each value, and it doesn’t keep the items in any particular order.
visits = [1, 2, 2, 3, 3, 3]
print(set(visits))
print(len(set(visits)))
Output:
{1, 2, 3}
3
The list has six items, but only three different values. Turning it into a set removes the repeats/duplicates, and len() of the set tells us how many different values there were.
Sets can also compare two collections. The & operator gives the items that appear in both:
print(set([1, 2, 3]) & set([2, 3, 4]))
Output:
{2, 3}
Where it’s used: Removing duplicates (for example, a list of repeated email addresses), counting how many different items there are, and finding what two groups have in common.
frozenset()
The frozenset() function creates a set that can’t be changed after it is created. It is the “locked” version of set().
fixed = frozenset([1, 2, 3])
print(fixed)
Output:
frozenset({1, 2, 3})
Trying to add to it gives an error:
frozenset([1, 2, 3]).add(4)
Output:
AttributeError: 'frozenset' object has no attribute 'add'
Where it’s used: When a set must stay the same, or when you need a set to be a dictionary key or an item inside another set. A normal set can’t be used for either.
dict()
The dict() function creates a dictionary, a collection that stores values under names called keys. You can create one by writing the pairs as keyword arguments, or by giving it a list of (key, value) pairs.
person = dict(name="Anna", age=30)
print(person)
print(person["name"])
print(dict([("a", 1), ("b", 2)]))
Output:
{'name': 'Anna', 'age': 30}
Anna
{'a': 1, 'b': 2}
Each pair connects a key to a value. person["name"] looks up the key name and returns Anna. In the last line, each small tuple in the list becomes one key and value pair.
list(), tuple(), set() and dict() are explained in more detail in Core Data Structures in Python.
Where it’s used: Storing records, such as a customer’s name and email, counting how often things occur, and looking up a value by its name. Data from the internet is usually in this format too.
bytes()
The bytes() function creates a bytes value, which is a sequence of numbers from 0 to 255 that can’t be changed. Each number stands for one byte of data. When the bytes represent text, each number is the code of a character.
print(bytes([72, 105]))
print(bytes("Hi", "utf-8"))
print(chr(72), chr(105))
Output:
b'Hi'
b'Hi'
H i
The first line turns the numbers 72 and 105 into the bytes for H and i, which Python displays as b'Hi'. The b in front shows that it’s bytes and not a string. The second line does it from text: it converts "Hi" using the "utf-8" encoding, the most common way to store text as bytes. The third line shows that 72 and 105 are the codes of H and i.
Where it’s used: Binary files such as images and PDFs, data sent over a network, and saving text in a file in a specific encoding.
bytearray()
The bytearray() function is like bytes(), but the result can be changed. You can replace single bytes after it is created.
data = bytearray(b"abc")
data[0] = 65
print(data)
Output:
bytearray(b'Abc')
65 is the code for the capital letter A. The line data[0] = 65 replaces the first byte (a) with it, so abc becomes Abc.
Where it’s used: Editing binary data in place, and building up binary data piece by piece, for example while reading a file or a network message in chunks.
memoryview()
The memoryview() function gives you a window onto the data inside a bytes or bytearray value, without making a copy of it. If the original can be changed, changes made through the view change the original too.
data = bytearray(b"abcdef")
view = memoryview(data)
view[0] = 65
print(view[1])
print(bytes(view[1:3]))
print(data)
Output:
98
b'bc'
bytearray(b'Abcdef')
view[1] is the number 98, which is the code for b. view[1:3] is a slice of the data, and bytes() shows it as b'bc'. The last line shows that data itself changed when we wrote view[0] = 65, which means the view and the original share the same memory.
Where it’s used: Working with large amounts of binary data, such as images, audio or big files, where copying the data again and again would be slow.
range()
The range() function creates a sequence of whole numbers. It can take one, two or three arguments:
range(5)counts from 0 up to, but not including, 5.range(2, 10)starts at 2 and stops before 10.range(2, 10, 3)also sets a step, so it counts in jumps of 3.
print(list(range(5)))
print(list(range(2, 10, 3)))
print(list(range(5, 0, -1)))
Output:
[0, 1, 2, 3, 4]
[2, 5, 8]
[5, 4, 3, 2, 1]
range() doesn’t make the numbers until they are needed, so we wrap it in list() to see them. In the first line, the numbers are 0, 1, 2, 3, 4. In the second, they are 2, 5, 8, and the next one, 11, would pass the stop value of 10. In the third, a negative step counts down from 5 to 1.
Where it’s used: for loops that repeat something a set number of times, as in Python Coding Exercise #58, and going through the positions of a list or a string.
Checking types
type()
The type() function tells you which type a value has.
print(type(5))
print(type("5"))
print(type(5.0))
print(type([1, 2]))
Output:
<class 'int'>
<class 'str'>
<class 'float'>
<class 'list'>
The number 5 and the text "5" look almost the same when printed, but type() shows that one is an int and the other a str.
Where it’s used: Finding out why a program doesn’t work as expected. A common case is a number that is really text because it came from input().
isinstance()
The isinstance() function checks whether a value is of a certain type, and returns True or False. You can give it a tuple of types, and it returns True if the value matches any of them.
print(isinstance(5, int))
print(isinstance("5", int))
print(isinstance(5.0, (int, float)))
Output:
True
False
True
The first line is True because 5 is an integer. The second is False, because "5" is a string. The third is True, because 5.0 is a float, one of the two types in the tuple.
A practical use is a function that behaves differently for different types:
def describe(value):
if isinstance(value, str):
return "text with " + str(len(value)) + " characters"
if isinstance(value, (int, float)):
return "a number"
return "something else"
print(describe("hello"))
print(describe(42))
print(describe([1, 2]))
Output:
text with 5 characters
a number
something else
Where it’s used: Checking that the data a function receives is the right type before using it, and choosing what to do depending on the type.
issubclass()
The issubclass() function checks whether one class is built on top of another one (its parent). For example, bool is built on int, which is why True behaves like the number 1.
print(issubclass(bool, int))
print(issubclass(str, int))
print(True + True)
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal))
Output:
True
False
2
True
True + True gives 2, because True is a kind of integer. The last line checks classes that we wrote ourselves: Dog is built on Animal, so the answer is True.
Where it’s used: Programs that use classes built on other classes, such as libraries and frameworks, to check that a class is allowed in a particular place.
callable()
The callable() function checks whether a value can be called, which means used with brackets like a function.
def greet():
return "Hello"
print(callable(greet))
print(callable(len))
print(callable("text"))
Output:
True
True
False
greet and len are functions, so they can be called. The string "text" can’t be, so the result is False.
Where it’s used: Checking a value before calling it, when it might be a function or might not, for example when a program lets you pass in your own function to run.
Numbers
abs()
The abs() function returns the absolute value of a number, which is its distance from zero. In simple words, it removes the minus sign.
print(abs(-7))
print(abs(-3.5))
print(abs(4))
Output:
7
3.5
4
The minus sign is dropped from -7 and -3.5, and a number without a minus sign stays the same.
This is useful to find the difference between two numbers when you don’t know which is larger:
print(abs(5 - 8))
print(abs(8 - 5))
Output:
3
3
Where it’s used: Finding the difference or the distance between two values, such as the gap between a target and an actual result, regardless of which one is bigger. Python Coding Exercise #13 compares an if version with abs().
round()
The round() function rounds a number. With one argument, it rounds to the nearest whole number. A second argument sets the number of decimal places to keep, and a negative second argument rounds to tens, hundreds and so on.
print(round(3.14159, 2))
print(round(1234, -2))
print(round(2.5))
print(round(3.5))
Output:
3.14
1200
2
4
round(3.14159, 2)keeps two decimal places and gives3.14.round(1234, -2)rounds to the nearest hundred and gives1200.round(2.5)andround(3.5)are exactly halfway between two whole numbers. In this case, Python rounds to the nearest even number, so2.5becomes2and3.5becomes4.
Where it’s used: Showing prices with two decimals, percentages and averages in a tidy way, as in Python Coding Exercise #22. Python Coding Exercise #14 uses it for money.
pow()
The pow() function raises a number to a power, which means multiplying it by itself a number of times. pow(2, 10) is 2 multiplied by itself 10 times, and it gives the same result as the ** operator.
A third argument gives the remainder after dividing the result by that number. This is faster than calculating the large power first, and then the remainder.
print(pow(2, 10))
print(2 ** 10)
print(pow(2, -1))
print(pow(2, 10, 1000))
Output:
1024
1024
0.5
24
pow(2, -1) gives 0.5, because a negative power means 1 divided by the number. In the last line, 2 to the power of 10 is 1024, and the remainder of 1024 divided by 1000 is 24.
A common formula that uses powers is growth over time. If 1000 grows by 5 percent every year, its value after 3 years is 1000 multiplied by 1.05 three times:
value = 1000 * pow(1.05, 3)
print(round(value, 2))
Output:
1157.63
Where it’s used: Formulas that involve growth or areas, such as compound interest and square or cube calculations, and, with the third argument, calculations in cryptography.
divmod()
The divmod() function divides one number by another, and returns two results together: how many times the second number fits completely (the quotient), and what is left over (the remainder).
print(divmod(17, 5))
quotient, remainder = divmod(17, 5)
print(quotient, remainder)
Output:
(3, 2)
3 2
5 fits into 17 three times (3 × 5 = 15), and 2 is left over. So the result is (3, 2). The second part of the example stores the two results in two variables.
A common use is converting minutes into hours and minutes:
hours, minutes = divmod(135, 60)
print(hours, "hours and", minutes, "minutes")
Output:
2 hours and 15 minutes
Where it’s used: Converting units (minutes to hours, centimetres to metres), working out how many full pages or boxes you need, and finding remainders.
min() and max()
The min() function returns the smallest value, and max() returns the largest. You can give them several values, or one collection.
Two optional arguments make them more flexible:
keyis a function that decides what to compare. Withkey=len, the values are compared by their length.defaultis what to return if the collection is empty. Without it, an empty collection gives an error.
print(min(3, 1, 2))
print(max([4, 9, 2]))
print(max(["apple", "fig", "banana"], key=len))
print(min([], default=0))
Output:
1
9
banana
0
The last two lines: max(..., key=len) returns banana, because it is the longest word, and min([], default=0) returns 0 because the list is empty. See Python Coding Exercise #23.
Where it’s used: Finding the lowest price, the highest score, the earliest or latest date, or the longest word in a list.
sum()
The sum() function adds up all the numbers in a collection. An optional second argument is the number to start from.
scores = [80, 90, 70]
print(sum(scores))
print(sum(scores, 10))
print(sum(scores) / len(scores))
Output:
240
250
80.0
The first line adds 80 + 90 + 70 to get 240. The second starts counting from 10, so it gives 250. The third line divides the total by the number of scores, which gives the average. Python Coding Exercise #50 uses sum() and len() to calculate a mean. Be careful not to name your own variable sum: Python Coding Exercise #09 shows what goes wrong.
Where it’s used: Totals and averages: the total of an order, the total of a month’s expenses, or the average of a set of scores.
bin(), oct() and hex()
Computers don’t count in tens like we do. We use the decimal system, with the digits 0 to 9. These three functions convert a whole number into text written in another number system:
bin()gives binary (base 2), which uses only 0 and 1.oct()gives octal (base 8), which uses the digits 0 to 7.hex()gives hexadecimal (base 16), which uses 0 to 9 and the letters a to f.
print(bin(10))
print(oct(8))
print(hex(255))
Output:
0b1010
0o10
0xff
The first two characters of each result show the system: 0b for binary, 0o for octal and 0x for hexadecimal. So 0b1010 is the binary number 1010, which is 8 + 2 = 10. These functions are the opposite of int(text, base), which you saw earlier:
print(int("1010", 2))
Output:
10
See Python Coding Exercise #24.
Where it’s used: Understanding how computers store numbers, reading and writing colour codes (hexadecimal colours like #FF5733 on the web), and working with file permissions (octal).
Characters and text
chr()
Every character, whether it’s a letter, a digit or a symbol, has a number code in a system called Unicode. The chr() function takes a code and returns the character that belongs to it.
print(chr(97))
print(chr(65))
print(chr(8364))
Output:
a
A
€
The code 97 is the lowercase letter a, 65 is the capital letter A, and 8364 is the euro sign.
Where it’s used: Generating letters from numbers, such as the alphabet, and encryption exercises like shifting every letter along by a few places.
ord()
The ord() function is the opposite of chr(). It takes a single character and returns its Unicode code number.
print(ord("a"))
print(ord("A"))
print(ord("€"))
Output:
97
65
8364
Since letters have consecutive codes, you can combine ord() and chr() to move through the alphabet. To get the letter 3 places after a, find its code, add 3, and convert back:
print(chr(ord("a") + 3))
Output:
d
Where it’s used: Comparing and sorting letters by their position, and ciphers (a simple secret code that shifts each letter).
ascii()
The ascii() function returns a version of a value that only contains basic ASCII characters (the English letters, digits and common symbols). Any other character is replaced by an escape code, a short code that starts with a backslash.
print(ascii("Café"))
Output:
'Caf\xe9'
The é is not in the basic set, so it becomes \xe9, which is its code written in hexadecimal.
Where it’s used: Showing text with special characters in a safe way, for example in logs, or in systems that can only display basic characters.
repr()
The repr() function returns the version of a value that shows exactly what it contains, the way you would write it in code. For a string, that means adding the quotes and showing hidden characters. The str() function gives the version meant for people to read.
print(str("hi"))
print(repr("hi"))
print(repr("line 1\nline 2"))
print(repr("hello "))
Output:
hi
'hi'
'line 1\nline 2'
'hello '
The first line shows hi without quotes. repr("hi") shows 'hi' with quotes. In the third line, repr() displays the line break as \n instead of actually breaking the line. The last line shows two spaces at the end of the text, which would be invisible if printed normally.
Where it’s used: Debugging. When something looks right on the screen but the program doesn’t behave correctly, repr() reveals hidden spaces and line breaks in the text.
format()
The format() function turns a single value into text using a format code, which describes how the value should look. This is the same set of codes that you can use inside f-strings.
print(format(3.14159, ".2f"))
print(format(255, "b"))
print(format(1234567, ","))
print(format(0.256, ".1%"))
Output:
3.14
11111111
1,234,567
25.6%
".2f"means a float with 2 digits after the decimal point."b"converts a whole number to binary.","adds a comma between groups of thousands.".1%"shows a fraction as a percentage with 1 decimal place.
Where it’s used: Displaying prices, large numbers with commas, and percentages in a readable way in reports and messages.
Working with collections
len()
The len() function returns the length of something: the number of characters in a string, or the number of items in a list, tuple, set or dictionary. See Python Coding Exercise #30.
print(len("hello"))
print(len([1, 2, 3]))
print(len({"a": 1, "b": 2}))
Output:
5
3
2
"hello" has 5 characters, the list has 3 items, and the dictionary has 2 key and value pairs. Spaces count as characters in a string.
A common use is checking that a text is long enough:
password = "python123"
if len(password) >= 8:
print("Long enough")
else:
print("Too short")
Output:
Long enough
Where it’s used: Checking the length of what a user typed, counting the items in a list, and working out averages (total divided by the number of items). Python Coding Exercise #55 compares the lengths of two strings, and Python Coding Exercise #59 uses the length to draw an underline.
sorted()
The sorted() function puts the items of a collection in order and returns them as a new list. The original collection stays the same. Two optional arguments change the order:
reverse=Truesorts from largest to smallest.keyis a function that decides what to sort by. For example,key=lensorts words by their length.
numbers = [3, 1, 2]
print(sorted(numbers))
print(sorted(numbers, reverse=True))
print(sorted(["banana", "fig", "apple"], key=len))
print(numbers)
Output:
[1, 2, 3]
[3, 2, 1]
['fig', 'apple', 'banana']
[3, 1, 2]
The last line shows that numbers is still [3, 1, 2]. The list method numbers.sort() is different: it changes the list itself and returns nothing. Use sorted() when you want to keep the original.
Words are sorted by their character codes, so capital letters come before lowercase ones. To sort without caring about case, use key=str.lower:
words = ["banana", "apple", "Cherry"]
print(sorted(words))
print(sorted(words, key=str.lower))
Output:
['Cherry', 'apple', 'banana']
['apple', 'banana', 'Cherry']
See Python Coding Exercise #02.
Where it’s used: Leaderboards, alphabetical lists of names, and ordering products by price or items by date. Python Coding Exercise #41 uses sorted() to find the middle of three letters.
reversed()
The reversed() function goes through a collection from the last item to the first. It returns an iterator (an object that hands out the items one at a time), so we wrap it in list() to see the items, or in "".join() to put letters back into a string.
print(list(reversed([1, 2, 3])))
print("".join(reversed("abc")))
Output:
[3, 2, 1]
cba
The list [1, 2, 3] comes out as [3, 2, 1], and the letters of abc are put back together as cba. A fun use of this is checking for a palindrome, a word that reads the same in both directions:
word = "level"
print(word == "".join(reversed(word)))
Output:
True
Where it’s used: Reading a text or a list backwards, checking palindromes, and showing the most recent item first.
enumerate()
The enumerate() function gives you each item of a collection together with its position number. It is used in for loops. By default, it counts from 0, and the start argument changes that.
for number, name in enumerate(["Anna", "Ben", "Chen"], start=1):
print(number, name)
Output:
1 Anna
2 Ben
3 Chen
In each round of the loop, enumerate() hands over a pair: the position and the item. The loop stores them in number and name. We used start=1, so the numbering begins at 1, as in a normal numbered list.
Where it’s used: Numbered lists and menus, and finding the position of an item while looping through a list.
zip()
The zip() function pairs up the items of two or more collections, the way a zip fastener joins the teeth on both sides. The first item from each collection forms the first pair, the second items form the second pair, and so on. It stops when the shortest collection runs out.
names = ["Anna", "Ben", "Chen"]
scores = [90, 85, 70]
print(list(zip(names, scores)))
for name, score in zip(names, scores):
print(name, "scored", score)
Output:
[('Anna', 90), ('Ben', 85), ('Chen', 70)]
Anna scored 90
Ben scored 85
Chen scored 70
The first line shows the pairs: Anna with 90, Ben with 85, and Chen with 70. The loop then takes one pair at a time. Combining zip() with dict() makes a dictionary:
names = ["Anna", "Ben", "Chen"]
scores = [90, 85, 70]
print(dict(zip(names, scores)))
Output:
{'Anna': 90, 'Ben': 85, 'Chen': 70}
Where it’s used: Combining related lists, such as names and scores, and building a dictionary from a list of keys and a list of values.
map()
The map() function applies a function to every item of a collection, and gives back the results. You pass it the function (without brackets) and the collection. It returns an iterator, so we wrap it in list() to see the items.
print(list(map(len, ["a", "bb", "cccc"])))
print(list(map(int, ["1", "2", "3"])))
print(list(map(str.strip, [" Anna ", "Ben "])))
Output:
[1, 2, 4]
[1, 2, 3]
['Anna', 'Ben']
map(len, ...)applieslento each word and gives their lengths.map(int, ...)converts each text to a number.map(str.strip, ...)removes the extra spaces around each name.
A very common use is turning one line of typed numbers into a list of numbers:
numbers = list(map(int, input("Numbers: ").split()))
print(numbers)
print(sum(numbers))
Output:
Numbers: 3 5 8
[3, 5, 8]
16
.split() cuts the typed text "3 5 8" into the list ["3", "5", "8"], map(int, ...) converts each piece to a number, and list() collects the results.
Where it’s used: Converting a whole list at once, such as text to numbers, and cleaning every item in a list of data.
filter()
The filter() function keeps only the items for which a function returns True. You pass it the function and the collection, and it returns an iterator with the items that passed the test.
def is_even(number):
return number % 2 == 0
print(list(filter(is_even, [1, 2, 3, 4, 5, 6])))
Output:
[2, 4, 6]
is_even returns True for numbers that leave no remainder when divided by 2. filter() calls it for each number and keeps only the even ones. If you pass None instead of a function, filter() keeps the items that count as true, which removes empty values:
print(list(filter(None, ["Anna", "", "Ben", "", "Chen"])))
Output:
['Anna', 'Ben', 'Chen']
Where it’s used: Selecting the items that match a rule, such as prices above a limit, and removing empty values from a list of data.
all() and any()
Both functions look at a collection of true and false values and give one answer:
all()returnsTrueonly if every item is true.any()returnsTrueif at least one item is true.
print(all([True, True, True]))
print(all([True, False, True]))
print(any([False, False, False]))
print(any([False, True, False]))
Output:
True
False
False
True
An empty collection can be surprising: all([]) is True, because there is no false item, and any([]) is False, because there is no true item.
They are useful to run several checks at once. Here, three rules are checked for a password, and all() tells us whether it passed all of them:
password = "python123"
checks = [
len(password) >= 8,
password.isalnum(),
password != "password",
]
print(checks)
print(all(checks))
Output:
[True, True, True]
True
Where it’s used: Validation, such as checking that every required field of a form is filled in (all), or that at least one answer matches (any).
slice()
The slice() function creates a slice object, which describes a cut with a start, a stop and a step. It is the same as writing start:stop:step inside square brackets, but you can store it in a variable and use the same cut more than once.
first_three = slice(0, 3)
for code in ["ABC123", "XYZ789"]:
print(code[first_three])
print("abc"[slice(None, None, -1)])
Output:
ABC
XYZ
cba
slice(0, 3) means “from position 0 up to, but not including, position 3”. We use it on two codes and get their first three letters. In the last line, None means “not specified”, and a step of -1 reads the text backwards.
Where it’s used: Cutting the same part out of many strings or lists, such as the first letters of every product code.
iter() and next()
An iterator is an object that hands out the items of a collection one at a time. The iter() function creates one from a collection, and the next() function asks it for the next item. When there are no items left, next() stops with an error, unless you give it a default value as a second argument.
items = iter([10, 20])
print(next(items))
print(next(items))
print(next(items, "no more items"))
Output:
10
20
no more items
The first two calls return 10 and 20. The third call has no items left, so it returns the default we gave it. Without a default, Python stops with StopIteration:
items = iter([10])
next(items)
next(items)
Output:
StopIteration
This is what a for loop does behind the scenes: it creates an iterator and calls next() until the items run out. You can use the same idea to handle the first item differently, such as a header row:
rows = iter(["name,age", "Anna,30", "Ben,25"])
header = next(rows)
print("Header:", header)
for row in rows:
print("Row:", row)
Output:
Header: name,age
Row: Anna,30
Row: Ben,25
Where it’s used: Going through data one item at a time, for example skipping the header line of a file, and understanding how for loops work.
aiter() and anext()
These are the asynchronous versions of iter() and next(). In an asynchronous program, tasks can wait for something, such as a reply from the internet, without stopping the rest of the program. Such a program uses the keywords async and await. They were added in Python 3.10.
import asyncio
async def count():
for number in range(3):
yield number
async def main():
items = aiter(count())
print(await anext(items))
print(await anext(items))
asyncio.run(main())
Output:
0
1
count() is an asynchronous generator that produces 0, 1 and 2. aiter() creates the iterator, and await anext(items) asks for the next value, one at a time. The first two values, 0 and 1, are printed.
Where it’s used: Asynchronous programs that read data as it arrives, such as web servers, programs that call online services, and live data streams.
Objects and classes
Some of the functions below work with classes and objects. A class is a blueprint, and an object is one thing built from that blueprint. For example, Course could be a class, and “Intro to Python” could be one course made from it. Values stored inside an object are called its attributes, and functions that belong to the class are called methods.
object()
The object() function creates a plain, empty object. In Python, every class is built on top of object, directly or indirectly. Even a class that you write without mentioning it is.
class Course:
pass
print(type(object()))
print(isinstance(Course(), object))
Output:
<class 'object'>
True
The first line shows the type of a plain object. The second shows that a Course we defined ourselves is also an object.
Where it’s used: It is the base of every class, and it is sometimes used to create a simple placeholder value.
id()
The id() function returns a number that identifies an object while the program runs. Two names with the same id() point to the very same object.
first = [1]
second = first
third = [1]
print(id(first) == id(second))
print(id(first) == id(third))
Output:
True
False
second = first doesn’t make a copy of the list. It gives the same list a second name, so the two ids are equal. third is a new list that happens to contain the same value, so its id is different. This matters because changing the list through one name changes it for the other:
first = [1]
second = first
second.append(2)
print(first)
Output:
[1, 2]
Where it’s used: Checking whether two names refer to the same object, which helps to understand why a list changed when you didn’t expect it.
hash()
The hash() function returns a number calculated from a value. Python uses this number to find items quickly in dictionaries and sets. The same value always gives the same hash during a run, and values that can be changed, such as lists, can’t be hashed.
print(hash(42))
print(hash("cat") == hash("cat"))
Output:
42
True
The hash of the number 42 is 42. Two equal strings have the same hash. A list has no hash:
print(hash([1, 2]))
Output:
TypeError: unhashable type: 'list'
This is why a list can’t be a dictionary key, while a string or a tuple can.
Where it’s used: Understanding how dictionaries and sets work, and checking whether a value can be used as a dictionary key.
dir()
The dir() function returns a list of the names of everything an object has: its attributes and methods. It is a way to find out what you can do with a value.
names = dir("text")
print("upper" in names)
print("append" in names)
print(names[-3:])
Output:
True
False
['translate', 'upper', 'zfill']
The string has an upper method but no append method (that one belongs to lists). The last line shows the final three names in the list, which are string methods. See String Methods in Python.
Where it’s used: Exploring a new module or object, and looking up the name of a method when you can’t remember it.
vars()
The vars() function returns the attributes of an object as a dictionary.
class Course:
def __init__(self, title, students):
self.title = title
self.students = students
course = Course("Intro to Python", 30)
print(vars(course))
Output:
{'title': 'Intro to Python', 'students': 30}
The Course object stores two attributes, title and students, and vars() shows them as a dictionary of names and values.
Where it’s used: Debugging, to see everything an object stores, and converting an object into a dictionary, for example to save it.
getattr(), setattr(), hasattr() and delattr()
These four functions work with an object’s attributes by name, where the name is given as a string:
getattr()reads an attribute. A third argument is a default value, used if the attribute doesn’t exist.setattr()sets an attribute.hasattr()checks whether an attribute exists.delattr()deletes an attribute.
class Course:
pass
course = Course()
setattr(course, "title", "Intro to Python")
print(getattr(course, "title"))
print(getattr(course, "level", "unknown"))
print(hasattr(course, "title"))
delattr(course, "title")
print(hasattr(course, "title"))
Output:
Intro to Python
unknown
True
False
The attribute title doesn’t exist at first, so setattr() creates it. getattr(course, "level", "unknown") returns the default, because there is no level. hasattr() is True before the deletion and False after it.
Using names as strings is useful when the name is only known while the program is running, for example when you go through a list of field names:
class Course:
pass
course = Course()
course.title = "Intro to Python"
for field in ["title", "level"]:
print(field, "=", getattr(course, field, "not set"))
Output:
title = Intro to Python
level = not set
Where it’s used: Reading and setting attributes whose names come from data, such as the column names of a spreadsheet, and checking for optional features.
property()
The property() function turns a method into something that is used like an attribute, without the brackets. The usual way to write it is with @property above the method.
In this example, the diameter is always calculated from the radius, so it stays correct even when the radius changes:
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def diameter(self):
return self.radius * 2
circle = Circle(5)
print(circle.diameter)
circle.radius = 8
print(circle.diameter)
Output:
10
16
We never set the diameter ourselves. Each time we read circle.diameter, Python runs the method and calculates the value from the current radius.
Where it’s used: Values that are calculated from other values, and attributes that need checking before they are changed.
classmethod() and staticmethod()
Both change how a method belongs to a class. They are usually written with @classmethod and @staticmethod above the method.
- A class method receives the class itself (usually called
cls) as its first argument. It is often used to create an object in a different way. - A static method receives nothing extra. It is an ordinary function that is kept inside the class because it belongs with it.
class Circle:
def __init__(self, radius):
self.radius = radius
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
@staticmethod
def is_valid_radius(value):
return value > 0
circle = Circle.from_diameter(10)
print(circle.radius)
print(Circle.is_valid_radius(-3))
Output:
5.0
False
from_diameter() is a second way to create a circle: it receives the class as cls, works out the radius, and creates the object with cls(...). is_valid_radius() doesn’t need any data from the circle, so it is a static method.
Where it’s used: Giving a class more than one way to create objects, and keeping small helper functions together with the class they belong to.
super()
When one class is built on another (a child class and its parent), the child inherits what the parent has. The super() function gives you access to the parent from inside the child. It is most often used to run the parent’s setup code, so you don’t have to write it again.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
dog = Dog("Rex", "Beagle")
print(dog.name, dog.breed)
Output:
Rex Beagle
Dog needs a name and a breed. The line super().__init__(name) runs the setup of Animal, which stores the name, and then Dog adds its own breed.
Where it’s used: Any program that uses inherited classes, to reuse the parent’s code and avoid repeating it.
Running code and files
eval()
The eval() function takes a string that contains a Python expression (a piece of code that produces a value), runs it, and returns the result.
print(eval("2 + 3 * 4"))
x = 10
print(eval("x * 2"))
Output:
14
20
The text "2 + 3 * 4" is treated as code, and gives 14. The second example shows that the code can use variables from your program.
Be careful with eval(): it runs whatever the text says. Never use it on text that comes from someone else, such as a user’s input, because it could run harmful code.
Where it’s used: Evaluating a formula that is stored as text, in programs where you control the text.
exec()
The exec() function runs a string as Python statements: assignments, loops and so on. Unlike eval(), it doesn’t give back a value. The same warning applies.
exec("total = 5 * 4\nprint(total)")
Output:
20
The string holds two lines of code, separated by \n. exec() runs both: it stores 20 in total, and prints it.
Where it’s used: Running code that is built while the program runs, for example in tools that run snippets of code.
compile()
The compile() function turns a string of Python code into a code object, which is code that is already prepared for running. Then eval() or exec() can run it as many times as you like, without preparing it again.
code = compile("3 * 4", "<string>", "eval")
print(eval(code))
print(eval(code))
Output:
12
12
The second argument is a name for the code, used in error messages, and "eval" says that the code is a single expression.
Where it’s used: Tools that run the same piece of code many times, and programs that process code.
globals() and locals()
Python keeps track of all the variable names in a dictionary:
globals()returns the names defined at the top level of the program.locals()returns the names in the place where it is called, for example inside a function.
language = "Python"
def show():
a = 1
b = 2
return locals()
print(globals()["language"])
print(show())
Output:
Python
{'a': 1, 'b': 2}
globals()["language"] looks up the variable language by its name. show() returns the two variables that exist inside the function.
Where it’s used: Debugging, to see which variables exist and what they contain.
breakpoint()
The breakpoint() function pauses the program on that line and opens the Python debugger. While it is paused, you can look at the variables and run the code one line at a time. It was added in Python 3.7. It waits for you to type, so only the code is shown here:
x = 10
breakpoint()
print(x)
When the program reaches breakpoint(), the debugger shows a prompt where you can type a command:
p xprints the value of the variablex.nruns the next line.ccontinues running the program normally.qquits.
Where it’s used: Finding out why a program isn’t doing what you expect, by stopping at the problem and looking at the values.
open()
The open() function opens a file and returns a file object, which you use to read from the file or write to it. The second argument is the mode:
| Mode | What it does |
|---|---|
"r" | Reads the file. This is the default. |
"w" | Writes to the file. If the file already exists, its content is replaced. |
"a" | Adds to the end of the file, and keeps what was there. |
The recommended way is with the with statement, which closes the file for you when the block ends.
with open("notes.txt", "w") as file:
file.write("first line\nsecond line\n")
with open("notes.txt", "a") as file:
file.write("third line\n")
with open("notes.txt") as file:
for line in file:
print(line.strip())
Output:
first line
second line
third line
The first block creates notes.txt with two lines. The second adds a third line at the end. The third reads the file one line at a time. Each line ends with a line break, so .strip() removes it before printing. For text with special characters, add encoding="utf-8" as an argument.
Where it’s used: Saving data so it is still there the next time the program runs, and reading text files, logs and spreadsheets saved as CSV.
Names that look like built-in functions, but aren’t quite
If you check Python’s list of built-in names, you will find five more: exit(), quit(), copyright(), credits() and license(). They are added by Python’s site module, to be typed in the interactive shell, and they are not available if Python is started in a special mode. In a program, use sys.exit() to stop it, and don’t rely on the others.
What is new in recent versions of Python
Some built-in functions have gained features over the years. Here are the changes that are most useful to know about.
zip() with strict=True (Python 3.10)
zip() normally stops quietly at the shortest collection, so data can go missing without any warning. With strict=True, it raises an error if the collections have different lengths.
names = ["Anna", "Ben", "Chen"]
scores = [90, 85]
print(list(zip(names, scores)))
Output:
[('Anna', 90), ('Ben', 85)]
There are three names but only two scores, and zip() silently leaves Chen out. With strict=True, the mismatch is reported:
names = ["Anna", "Ben", "Chen"]
scores = [90, 85]
print(list(zip(names, scores, strict=True)))
Output:
ValueError: zip() argument 2 is shorter than argument 1
map() with strict=True (Python 3.14)
The same option was added to map() in Python 3.14, for when it is given more than one collection.
print(list(map(pow, [2, 3, 4], [1, 2], strict=True)))
Output:
ValueError: map() argument 2 is shorter than argument 1
sum() is more accurate with decimals (Python 3.12)
Decimal numbers are stored with tiny rounding errors. Since Python 3.12, sum() adds decimal numbers in a way that keeps more accuracy, so adding 0.1 ten times now gives exactly 1.0. In older versions, the result was 0.9999999999999999.
print(sum([0.1] * 10))
Output:
1.0
isinstance() accepts | (Python 3.10)
Instead of a tuple of types, you can join the types with |, which reads like “this type or that type”.
print(isinstance(5, int | float))
print(isinstance("5", int | float))
Output:
True
False
New functions: aiter(), anext() and breakpoint()
These three are covered above. breakpoint() arrived in Python 3.7, and aiter() and anext() in Python 3.10. None of the three is on the W3Schools list of built-in functions.
Which function do I need?
| I want to… | Use |
|---|---|
| Show something on the screen | print() |
| Ask the user for text | input() |
| Convert between text and numbers | int(), float(), str() |
| Know how many items or characters there are | len() |
| Find the smallest, largest or total | min(), max(), sum() |
| Round a number | round() |
| Sort a collection | sorted() |
| Repeat something a set number of times | range() |
| Loop with a position number | enumerate() |
| Loop over two lists together | zip() |
| Apply a function to every item | map() |
| Keep only the items that match a rule | filter() |
| Check whether all or any items are true | all(), any() |
| Check the type of a value | type(), isinstance() |
| Read the documentation of something | help() |
| Read or write a file | open() |
Key takeaways
- Built-in functions are always available, with no
importneeded. - Many of them, like
int(),str()andlist(), are really classes, but you call them in the same way. print()andinput()handle output and input, andinput()always returns a string.int(),float(),str(),bool(),list(),tuple(),set()anddict()create or convert values.int(text, base)reads a number written in another number system.len(),min(),max(),sum(),sorted()andround()are the ones you will use most for data.sorted(),reversed(),map(),filter()andzip()don’t change the original collection.enumerate()andzip()makeforloops cleaner.eval()andexec()run text as code, so never use them on text from other people.- Newer versions of Python added
aiter(),anext()andbreakpoint(), and gavezip(),map(),sum()andisinstance()new abilities.
Where to find the full list
For the complete official description, see the Python documentation on built-in functions. To work with strings in more depth, read String Methods in Python.
✦ Thanks for reading! ✦