Skip to main content

Built-in Functions

Updated Oct 29, 2019 ·

Overview​

Python has many built-in functions to simplify tasks. Some functions are used often are:

  • print(): Displays output.
  • type(): Shows the type of a value.
  • range(): Generates numbers, often used in loops.

Finding Min and Max​

Python makes working with numbers easy.

  • max(): Finds the highest value in a list.
  • min(): Finds the lowest value.
sales = [200, 150, 300, 100]
print(max(sales)) # 300
print(min(sales)) # 100

Summing and Rounding​

We can calculate totals and round numbers.

  • sum(): Adds up all values in a list.
  • round(): Rounds a number to a set number of decimal places.
total_sales = sum(sales)
rounded_sales = round(total_sales, 2)
print(rounded_sales)

Chained Function Calls​

Functions can be called inside other function calls to process data step by step in a single line.

  • Inner functions run first
  • Each result is passed to the next function
  • The final result is used by the outer function

In the example below, the variable sales is a list of numbers. The function sum runs first, its result is passed to round, and the final value is printed.

sales = [200, 150, 300, 100]

print(round(sum(sales), 2)) # Output: 750

Counting Items​

We can count elements using len(). This works on lists, strings, dictionaries, sets, and tuples.

print(len(sales)) # 4 transactions
print(len("Hello World")) # 11 characters (including space)

Sorting Data​

We can sort lists and strings.

  • sorted(): Orders values in ascending order.
print(sorted(sales)) # [100, 150, 200, 300]
print(sorted("Alice")) # ['A', 'c', 'e', 'i', 'l']

Getting Help​

The help() function provides details about other functions.

help(sorted)

It shows arguments like key and reverse, which modify sorting behavior.

Why Use Functions?​

Functions save time and reduce mistakes. For example, instead of looping manually, we use built-in functions like sum().

total = 0
for sale in sales:
total += sale
print(total) # Same as sum(sales)

Using sum(sales) is shorter and cleaner.