Python Built-in FunctionsGet Certified
What Are Built-in Functions in Python?
Built-in functions are ready-made tools that come with Python itself. You do not need to install anything or write an import line to use them. You have already met several, such as print(), input(), len(), and range().
Python includes more than seventy built-in functions, and a handful of them solve a large share of everyday problems: counting items, adding numbers, converting types, sorting data, and looping with positions. Learning them well saves you from writing code that Python has already written, tested, and optimized for you.
- Always available: built-in functions work in every Python program with no import.
- Summarize data:
len(),sum(),min(), andmax()describe a collection. - Convert and check types:
int(),float(),str(),bool(),list(),type(), andisinstance(). - Loop helpers:
range(),enumerate(), andzip()make loops shorter and clearer. - Sort and test:
sorted(),reversed(),any(), andall(). - Math and text:
abs(),round(),pow(),divmod(),ord(), andchr().
Counting and Summarizing with len, sum, min, and max
Four built-in functions give you a quick summary of any list of numbers. len() counts the items, sum() adds them, and min() and max() find the smallest and largest values. With these four you can calculate an average without writing a single loop.
They also work on other collections, such as tuples, sets, and strings. abs() gives the distance of a number from zero, and round() controls how many decimal places you keep. Remember that min() and max() raise a ValueError if the collection is empty.
Try It: Summarize a Week of Temperatures
Click Test My Code to run the program. Then replace the numbers with a week of weather from your own city.
abs(), round(), and pow().temps = [58, 71, 64, 49, 77]
print(len(temps))
print(sum(temps))
print(min(temps), max(temps))
print(round(sum(temps) / len(temps), 1))
print(abs(-12), round(3.14159, 2), pow(2, 5))temps holds five daily high temperatures.len() returns the number of items in the list. The output is 5.sum() adds all the numbers: 58 + 71 + 64 + 49 + 77. The output is 319.min() returns the coldest day and max() returns the warmest day. The output is 49 77.round(..., 1) keeps one decimal place. The output is 63.8.abs(-12) is 12, round(3.14159, 2) is 3.14, and pow(2, 5) is 2 to the power of 5, which is 32. The output is 12 3.14 32.Converting and Checking Types
Data often arrives as text, such as an age typed into a form or a ZIP code read from a file. The conversion functions int(), float(), str(), bool(), and list() turn a value into the type you need. They create a new value and leave the original unchanged.
To find out what type a value has, use type(). To test for a type in an if statement, isinstance() is the better choice. Be careful with conversions that cannot work, such as int("abc"), because Python raises a ValueError.
Try It: Convert Form Data
Click Test My Code. Then change the values to your own age and ZIP code.
bool() and list().age = int("19")
gpa = float("3.75")
zip_code = str(78701)
print(type(age), type(gpa), type(zip_code))
print(isinstance(age, int))
print(bool(0), bool("Texas"), list("USA"))int("19") converts the text "19" to the whole number 19.float("3.75") converts the text to the decimal number 3.75.str(78701) makes the text "78701". ZIP codes are better stored as text because you never calculate with them.type() reports the type of each value. The output is <class 'int'> <class 'float'> <class 'str'>.isinstance(age, int) is True because age is an integer.bool(0) is False and bool("Texas") is True, because only zero and empty values are false. list("USA") splits the text into letters. The output is False True ['U', 'S', 'A'].Looping Helpers: range, enumerate, and zip
Three built-in functions make for loops shorter and safer. range() produces a sequence of numbers, enumerate() gives you each item together with its position, and zip() walks through two or more lists side by side. They replace the clumsy pattern of counting with an index variable.
All three return lazy objects that produce values only when the loop asks for them. That makes them memory friendly even for very large ranges. Wrap them in list() when you want to see all the values at once, as the last line of the example does.
Try It: Number and Pair Up American Cities
Click Test My Code. Then add a fourth city and state to both lists.
range().cities = ["Austin", "Boston", "Denver"]
states = ["TX", "MA", "CO"]
for number, city in enumerate(cities, start=1):
print(number, city)
for city, state in zip(cities, states):
print(city + ", " + state)
print(list(range(0, 10, 3)))enumerate(cities, start=1) produces pairs of a counter and an item. Without start=1 the counter would begin at 0.1 Austin, 2 Boston, and 3 Denver, one per line.zip(cities, states) walks through both lists together and produces ("Austin", "TX"), ("Boston", "MA"), and ("Denver", "CO").Austin, TX, Boston, MA, and Denver, CO.range(0, 10, 3) starts at 0, stops before 10, and steps by 3. The output is [0, 3, 6, 9].Sorting and Testing Collections
sorted() returns a new, ordered list and leaves the original alone, while reversed() walks through a sequence from the end. The functions any() and all() answer yes-or-no questions about a whole collection: any() is True if at least one item passes, and all() is True only if every item passes.
Together they replace many short loops. You can ask whether anyone failed, whether everyone passed, or what the top three values are. They pair especially well with a generator expression, which tests each item as it is produced without building a temporary list.
Try It: Analyze Exam Scores
Click Test My Code. Then change a score and see how the last two answers change.
scores = [88, 92, 79, 65, 95]
print(sorted(scores))
print(sorted(scores, reverse=True)[:3])
print(list(reversed(scores)))
print(any(s < 70 for s in scores))
print(all(s >= 60 for s in scores))sorted() returns a new list. The output is [65, 79, 88, 92, 95], and scores itself is unchanged.reverse=True sorts from high to low, and the slice [:3] keeps the first three. The output is [95, 92, 88].reversed() walks backward through the original list. list() collects the values. The output is [95, 65, 79, 92, 88].any() stops at the first True. The score 65 is below 70, so the output is True.all() is True only when every test passes. All five scores are 60 or higher, so the output is True.Math Helpers: divmod, round, pow, max, and min
Python’s math helpers handle common calculations in a single call. divmod(a, b) returns the quotient and the remainder together, which is perfect for converting minutes into hours and minutes. pow() raises a number to a power and can also calculate a remainder in the same step.
Be aware that round() uses “banker’s rounding”: a value exactly halfway between two whole numbers goes to the nearest even number, so round(8.5) is 8. Decimal numbers are also stored in binary, so round(2.675, 2) gives 2.67. Finally, max() and min() accept several separate values and even strings.
Try It: Flight Time from New York to Los Angeles
Click Test My Code. Then change the number of minutes to another flight time.
divmod(), shows how round() treats halves, compares text and numbers with max() and min(), and uses pow() with and without a modulus.minutes = 375
hours, mins = divmod(minutes, 60)
print(hours, "hours", mins, "minutes")
print(round(2.675, 2), round(7.5), round(8.5))
print(max("apple", "banana"), min(3, 9, 1))
print(pow(2, 10), pow(2, 10, 1000))divmod(375, 60) returns the pair (6, 15), which is unpacked into hours and mins.6 hours 15 minutes.round(2.675, 2) gives 2.67 because 2.675 cannot be stored exactly in binary. Halves round to the nearest even number, so round(7.5) is 8 and round(8.5) is also 8. The output is 2.67 8 8.max() on strings picks the one that comes last alphabetically, which is banana. min(3, 9, 1) is 1. The output is banana 1.pow(2, 10) is 1024. With a third argument, pow(2, 10, 1000) gives the remainder of 1024 divided by 1000, which is 24. The output is 1024 24.Printing and Formatting Output
You already know print(), but it has two useful options. The sep option sets the text placed between items, and end sets what is printed at the very end, which is a new line by default. Changing them lets you build tidy output without extra string work.
For nicer numbers, format() converts a value to text using a format code, such as adding commas to a large number. repr() shows a value the way Python would write it in code, which is very helpful for spotting hidden quotes or spaces when you are debugging.
Try It: Format Travel Output
Click Test My Code. Then change the separator or the number to see how the output changes.
print() calls on one line, formats a large number with commas, and shows the code form of an airport name.print("Boston", "Chicago", "Seattle", sep=" -> ")
print("Loading", end="...")
print("done")
print(format(1234567.891, ",.2f"))
print(repr("O'Hare"))sep=" -> " replaces the default space between the items. The output is Boston -> Chicago -> Seattle.end="..." prints three dots instead of a new line, so the next output continues on the same line.done appears right after the dots. Together, lines 2 and 3 output Loading...done.",.2f" means commas between thousands and two decimal places. The output is 1,234,567.89.repr() returns the text as Python would write it. Because the name contains an apostrophe, Python uses double quotes. The output is "O'Hare".Working with Characters and Strings
Several built-in functions work well with text. ord() turns a character into its numeric code, and chr() turns a code back into a character. Because a string is a sequence of characters, len(), sorted(), reversed(), min(), and max() all work on strings too.
Characters are compared by their numeric codes, so all uppercase letters come before all lowercase letters. That is why "H" is smaller than "a". Convert text with .lower() first when you want a case-insensitive result. The "".join() method glues a sequence of characters back into one string.
Try It: Play with the Word Houston
Click Test My Code. Then change the word to your own hometown.
print(ord("A"), chr(66))
word = "Houston"
print(sorted(word.lower()))
print("".join(reversed(word)))
print(len(word), max(word), min(word))ord("A") is 65 and chr(66) is "B". The output is 65 B.word holds the name of a Texas city.word.lower() makes all letters lowercase, and sorted() returns the letters in alphabetical order as a list. The output is ['h', 'n', 'o', 'o', 's', 't', 'u'].reversed(word) walks backward through the letters, and "".join() glues them together. The output is notsuoH.len(word) is 7. The largest character by code is u, and the smallest is the capital H, because uppercase codes are lower than lowercase codes. The output is 7 u H.Using Built-in Functions with input()
Built-in functions shine when you combine them with user input. The function input() returns text, split() breaks it into pieces, int() converts each piece to a number, and then len(), sum(), min(), and max() summarize the data in a few lines.
This is the pattern behind countless small programs: read some values, convert them, and report the results. If a piece of the input is not a number, int() raises a ValueError, so always enter the values exactly as the prompt describes.
Try It: Summarize a Houston Commute
The Program Input box is already filled with one line: Houston 45 38 52 41. Click Run Code straight away, then try another city followed by your own commute times in minutes.
line = input("City and daily commute minutes: ")
parts = line.split()
city = parts[0]
minutes = [int(p) for p in parts[1:]]
print(city, "trips:", len(minutes))
print("Total:", sum(minutes), "minutes")
print("Average:", round(sum(minutes) / len(minutes), 1))
print("Longest:", max(minutes), "Shortest:", min(minutes))input() reads the first line of the Program Input box as a single string, such as "Houston 45 38 52 41".split() breaks the string at the spaces into the list ['Houston', '45', '38', '52', '41'].parts[0], is the city name.parts[1:] is every item after the city. The comprehension converts each one with int(), giving [45, 38, 52, 41].len(minutes) is 4. The output is Houston trips: 4.sum(minutes) is 176. The output is Total: 176 minutes.round(..., 1) keeps one decimal place. The output is Average: 44.0.max() finds the longest trip and min() finds the shortest. The output is Longest: 52 Shortest: 38.Tip: You can see every built-in name by typingdir(__builtins__)in a Python session, and you can read what any of them does by callinghelp(), for examplehelp(sorted).
Common Mistakes with Built-in Functions
Because built-in functions are so convenient, it is easy to use them without thinking about what they accept and what they return. Most errors come from the wrong type of argument or from overwriting a built-in name by accident. Python’s error messages usually point straight to the line, so read them carefully.
- Naming a variable after a built-in:
list = [1, 2, 3]orsum = 0hides the built-in, and a laterlist("abc")orsum(scores)fails with aTypeError. Use names such asnumbersandtotal. - Forgetting that input() returns text:
sum(input().split())fails because the pieces are strings. Convert them withint()orfloat()first. - Converting invalid text:
int("3.5")andint("abc")raise aValueError. Usefloat()for decimal text. - Empty collections:
max([])raises aValueErrorandsum(minutes) / len(minutes)fails with aZeroDivisionErrorwhen the list is empty. - Calling len() on a number:
len(12345)raises aTypeError. Convert withstr()first if you want to count digits. - Expecting lazy objects to be lists:
range(),zip(),reversed(), andenumerate()produce values on demand. Wrap them inlist()to see all the values. - Reusing an exhausted iterator: a
zip()orreversed()object can be looped over only once. - Expecting round() to round halves up:
round(2.5)is2, not3, because halves go to the nearest even number.
Good Habits for Using Built-in Functions
Before you write a loop to calculate something, ask whether Python already has a built-in function for it. Built-in functions are fast, well tested, and familiar to every Python programmer, which makes your code easier for others to read. These habits will help you get the most out of them.
- Check for a built-in first. Use
sum(),max(),sorted(),any(), andall()instead of writing the same loops by hand. - Never use a built-in name, such as
list,str,max,sum, orinput, as a variable name. - Use
enumerate()instead ofrange(len(items))when you need positions, andzip()when you walk through two lists together. - Use
sorted()when you need a new list and keep the original data unchanged. - Check that a collection is not empty before calling
min(),max(), or dividing bylen(). - Use
help()and the official Python documentation to learn the options of a function, such askeyandreverseforsorted().
Key Takeaways
Built-in functions are the foundation of everyday Python. With only a dozen of them you can summarize data, convert types, loop with positions, sort, and format output. Review the points below before moving on to modules and the import statement, which give you access to even more tools.
- Built-in functions are always available and need no
import. len(),sum(),min(), andmax()summarize a collection quickly.int(),float(),str(),bool(), andlist()convert types, andtype()andisinstance()check them.range(),enumerate(), andzip()make loops shorter and clearer.sorted()returns a new sorted list, andany()andall()test a whole collection.divmod(),round(),pow(), andabs()handle common math jobs.- Do not give variables the same name as a built-in function.
Frequently Asked Questions
Students often wonder how many built-in functions there are, how to find them, and why a few of them behave in surprising ways. The answers below are short and use the same rules you practiced in the examples. Open a question to read the answer, and run the matching example again if you want to see it in action.
What are built-in functions in Python?
Built-in functions are functions that are always available in Python without any import. Examples include print(), len(), sum(), max(), range(), and sorted(). Python provides more than seventy of them for common tasks.
How can I see all the built-in functions in Python?
Type dir(__builtins__) in a Python session to list every built-in name, and call help() on any of them, such as help(sorted), to read what it does. The official Python documentation also has a complete table of built-in functions.
What is the difference between sorted() and list.sort()?
sorted() accepts any iterable and returns a new sorted list, leaving the original unchanged. The sort() method belongs to lists, sorts the list in place, and returns None. Use sorted() when you still need the original order.
What do enumerate() and zip() do?
enumerate() pairs each item of an iterable with its position, as in enumerate(cities, start=1). zip() combines two or more iterables item by item, as in zip(cities, states). Both are used in for loops and stop at the end of the shortest input.
Why does round(2.5) return 2 in Python?
Python uses banker’s rounding, which rounds a value exactly halfway between two integers to the nearest even number. So round(2.5) is 2 and round(3.5) is 4. Decimal numbers are also stored in binary, so round(2.675, 2) gives 2.67.
Why should I not name a variable list or sum?
Assigning to a built-in name hides the built-in function in that scope. After sum = 0, calling sum(scores) raises a TypeError because sum is now a number. Choose descriptive names such as numbers or total instead.
What is the difference between int() and float()?
int() converts a value to a whole number, and float() converts it to a decimal number. int(“19”) gives 19 and float(“3.75”) gives 3.75. int(“3.5”) raises a ValueError, so use float() for text with a decimal point.
What happens if I call min() or max() on an empty list?
Python raises a ValueError because there is no smallest or largest item. You can avoid the error by checking that the list is not empty first, or by passing the default argument, as in max(scores, default=0).