Academic Block

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(), and max() describe a collection.
  • Convert and check types: int(), float(), str(), bool(), list(), type(), and isinstance().
  • Loop helpers: range(), enumerate(), and zip() make loops shorter and clearer.
  • Sort and test: sorted(), reversed(), any(), and all().
  • Math and text: abs(), round(), pow(), divmod(), ord(), and chr().

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.

What this code does: It counts, adds, and finds the smallest and largest of five daily temperatures in Fahrenheit, calculates the average, and then shows 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))

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.

What this code does: It converts text to an integer and a float, turns a ZIP code number into text, shows the type of each value, and demonstrates 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"))

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.

What this code does: It numbers a list of cities starting at 1, pairs each city with its state abbreviation, and prints a list made with 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)))

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.

What this code does: It sorts five exam scores, finds the top three, reverses the original order, and checks whether any score is below 70 and whether all scores are at least 60.
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))

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.

What this code does: It converts 375 flight minutes into hours and minutes with 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))

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.

What this code does: It prints three cities joined by arrows, keeps two 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"))

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.

What this code does: It shows the numeric code of a letter, sorts the letters of a city name, reverses the name, and reports its length together with its largest and smallest characters.
print(ord("A"), chr(66))
word = "Houston"
print(sorted(word.lower()))
print("".join(reversed(word)))
print(len(word), max(word), min(word))

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.

What this code does: It reads a city name followed by commute times, converts the times to integers, and prints the number of trips, the total, the average, and the longest and shortest trips.
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))
Tip: You can see every built-in name by typing dir(__builtins__) in a Python session, and you can read what any of them does by calling help(), for example help(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] or sum = 0 hides the built-in, and a later list("abc") or sum(scores) fails with a TypeError. Use names such as numbers and total.
  • Forgetting that input() returns text: sum(input().split()) fails because the pieces are strings. Convert them with int() or float() first.
  • Converting invalid text: int("3.5") and int("abc") raise a ValueError. Use float() for decimal text.
  • Empty collections: max([]) raises a ValueError and sum(minutes) / len(minutes) fails with a ZeroDivisionError when the list is empty.
  • Calling len() on a number: len(12345) raises a TypeError. Convert with str() first if you want to count digits.
  • Expecting lazy objects to be lists: range(), zip(), reversed(), and enumerate() produce values on demand. Wrap them in list() to see all the values.
  • Reusing an exhausted iterator: a zip() or reversed() object can be looped over only once.
  • Expecting round() to round halves up: round(2.5) is 2, not 3, 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(), and all() instead of writing the same loops by hand.
  • Never use a built-in name, such as list, str, max, sum, or input, as a variable name.
  • Use enumerate() instead of range(len(items)) when you need positions, and zip() 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 by len().
  • Use help() and the official Python documentation to learn the options of a function, such as key and reverse for sorted().

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(), and max() summarize a collection quickly.
  • int(), float(), str(), bool(), and list() convert types, and type() and isinstance() check them.
  • range(), enumerate(), and zip() make loops shorter and clearer.
  • sorted() returns a new sorted list, and any() and all() test a whole collection.
  • divmod(), round(), pow(), and abs() 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).

Ready for the next step?Learn how to organize code into files and use tools from the Python standard library.
Next: Modules, Packages & import →