upgrade
upgrade

🐍Intro to Python Programming

Common Python Built-in Functions

Study smarter with Fiveable

Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.

Get Started

Why This Matters

Python's built-in functions are the foundation of everything you'll write in this course. Whether you're processing user input, manipulating data structures, or debugging your code, these functions appear in virtually every program you'll create. Understanding when and why to use each function—not just what it does—separates students who struggle through assignments from those who code fluently.

You're being tested on your ability to choose the right tool for the job, convert between data types correctly, and work with collections efficiently. Don't just memorize syntax—know which functions handle input/output, which ones transform data types, which ones work with sequences, and which ones perform calculations. That conceptual framework will help you solve problems you've never seen before.


Input and Output Functions

These functions handle communication between your program and the outside world. Every interactive program needs a way to receive data and display results.

print()

  • Displays output to the console—the primary way your program communicates results to users
  • Multiple arguments separated by commas are automatically joined with spaces; use sep parameter to customize the separator
  • The end parameter controls what prints after your output; defaults to newline (\n) but can be changed for same-line printing

input()

  • Reads user input as a string—always returns a string, even if the user types numbers
  • Optional prompt argument displays a message telling users what to enter: input("Enter your name: ")
  • Requires type conversion for numerical operations; forgetting this is one of the most common beginner bugs

Compare: print() vs. input()—both handle console interaction, but print() sends data out while input() brings data in. Remember: input() always returns a string, so input("Number: ") + 1 will crash without conversion.


Type Conversion Functions

These functions transform data from one type to another. Python is dynamically typed, but operations often require specific types—conversion functions bridge that gap.

int()

  • Converts values to integers—truncates decimals (doesn't round), so int(3.9) returns 3
  • Parses string numbers like int("42"), essential for processing input() results
  • Raises ValueError if the string can't be converted; int("hello") crashes your program

float()

  • Converts values to floating-point numbers—allows decimal precision for calculations
  • Handles both integers and strings: float(5) returns 5.0, float("3.14") returns 3.14
  • Required for division results when you need decimal accuracy rather than truncated integers

str()

  • Converts any value to a string—necessary for concatenating numbers with text
  • Solves the concatenation error: "Score: " + str(95) works; "Score: " + 95 crashes
  • Useful for formatting output when you need precise control over how values display

Compare: int() vs. float()—both convert to numbers, but int() discards decimals while float() preserves them. Choose based on whether your calculation needs decimal precision. For user input that could be either, float() is safer.


Type Inspection Functions

These functions help you understand what you're working with. Debugging and writing flexible code requires knowing your data types.

type()

  • Returns the data type of any object—essential for debugging "why isn't this working?" moments
  • Reveals hidden type mismatches: when "5" + 5 fails, type() shows you one is <class 'str'>
  • Useful in conditionals to handle different input types: if type(x) == int:

len()

  • Returns the count of items in sequences (strings, lists, tuples) and collections (dictionaries, sets)
  • Critical for loop control: for i in range(len(my_list)): iterates through indices
  • Input validation tool—check if user input meets length requirements before processing

Compare: type() vs. len()—both inspect objects, but type() tells you what kind of data you have while len() tells you how much. Use type() for debugging type errors; use len() for size validation and loop control.


Data Structure Constructors

These functions create Python's core collection types. Understanding when to use each structure is fundamental to organizing data effectively.

list()

  • Creates a mutable sequence—items can be added, removed, or changed after creation
  • Converts iterables to lists: list("hello") returns ['h', 'e', 'l', 'l', 'o']
  • Stores mixed types—a single list can hold integers, strings, and other lists together

dict()

  • Creates key-value pair collections—each unique key maps to a value for fast lookups
  • Alternative syntax: dict(name="Alice", age=20) creates {'name': 'Alice', 'age': 20}
  • O(1)O(1) average lookup time—retrieving values by key is extremely fast regardless of dictionary size

range()

  • Generates a sequence of integers—not a list, but an efficient iterable for loops
  • Three-argument form: range(start, stop, step) controls where to begin, end, and how to increment
  • Stop value is exclusive: range(1, 5) produces 1, 2, 3, 4—not including 5

Compare: list() vs. dict()—both store collections, but lists use numeric indices while dictionaries use custom keys. Use lists for ordered sequences; use dictionaries when you need to look up values by meaningful names (like student IDs or usernames).


Mathematical and Aggregate Functions

These functions perform calculations on numbers and collections. They replace manual loops for common operations, making code cleaner and faster.

sum()

  • Totals all items in an iterablesum([1, 2, 3, 4]) returns 10
  • Optional start parameter: sum([1, 2, 3], 10) returns 16 (adds 10 to the total)
  • Only works with numbers—attempting to sum strings raises a TypeError

max()

  • Returns the largest value—works on iterables or multiple arguments: max(3, 7, 2) or max([3, 7, 2])
  • Key parameter enables custom comparisons: max(words, key=len) finds the longest string
  • Raises ValueError on empty sequences—always check that your list has items first

min()

  • Returns the smallest value—mirror of max() with identical syntax options
  • Same key parameter flexibility: min(students, key=lambda s: s['grade']) finds lowest grade
  • Useful for finding bounds—often paired with max() to establish ranges

abs()

  • Returns absolute value—removes negative signs, so abs(-7) returns 7
  • Essential for distance calculations: difference between values regardless of order
  • Works with floats too: abs(-3.14) returns 3.14

Compare: max() vs. min()—identical syntax and behavior, just opposite results. Both accept the key parameter for custom comparisons. When finding both extremes, call them together: lowest, highest = min(data), max(data).


Sorting Functions

This function reorders sequences. Organizing data is fundamental to analysis and display.

sorted()

  • Returns a new sorted list—original sequence unchanged, unlike the .sort() method
  • Reverse parameter: sorted(nums, reverse=True) sorts in descending order
  • Key parameter enables custom sorting: sorted(names, key=str.lower) ignores case

Compare: sorted() vs. list.sort()sorted() creates a new list and works on any iterable, while .sort() modifies the original list in place and only works on lists. Use sorted() when you need to preserve the original order.


Quick Reference Table

ConceptBest Examples
Console I/Oprint(), input()
String Conversionstr(), int(), float()
Type Inspectiontype(), len()
Collection Constructorslist(), dict(), range()
Aggregationsum(), max(), min()
Sortingsorted()
Mathematicalabs(), sum()
Loop Controlrange(), len()

Self-Check Questions

  1. Which two functions would you use together to get a number from the user and use it in a calculation? Why is using just input() insufficient?

  2. You have a list of test scores and need to find the range (difference between highest and lowest). Which built-in functions would you combine to calculate this?

  3. Compare list() and dict()—when would you choose one over the other for storing student information?

  4. Your code crashes with "can only concatenate str (not 'int') to str." Which built-in function would you use to fix this, and where would you apply it?

  5. Explain the difference between sorted(my_list) and my_list.sort(). In what situation would choosing the wrong one cause a bug in your program?